<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="utf-8"><title>Angular - 测试</title><meta name="Description" content="Angular is a platform for building mobile and desktop web applications.
    Join the community of millions of developers who build compelling user interfaces with Angular."><base href="/"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="search" type="application/opensearchdescription+xml" href="assets/opensearch.xml"><link rel="icon" type="image/x-icon" href="assets/images/favicons/favicon.ico"><link rel="icon" type="image/png" href="assets/images/favicons/favicon-32x32.png" sizes="32x32"><link rel="icon" type="image/png" href="assets/images/favicons/favicon-194x194.png" sizes="194x194"><link rel="icon" type="image/png" href="assets/images/favicons/favicon-96x96.png" sizes="96x96"><link rel="icon" type="image/png" href="assets/images/favicons/favicon-16x16.png" sizes="16x16"><link rel="apple-touch-icon" sizes="144x144" href="assets/images/favicons/favicon-144x144.png"><link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/images/favicons/favicon-144x144.png"><link href="assets/fonts/Material_Icons.css" rel="stylesheet"><link href="assets/fonts/Droid_Sans_Mono.css" rel="stylesheet"><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"><link rel="manifest" href="pwa-manifest.json"><meta name="theme-color" content="#1976d2"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="translucent"><script async="" src="assets/js/analytics.js"></script><script>!function(e,a,n,t,s,c,g){e.GoogleAnalyticsObject=s,e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,c=a.createElement(n),g=a.getElementsByTagName(n)[0],c.async=1,c.src="assets/js/analytics.js",~e.name.indexOf("NG_DEFER_BOOTSTRAP")||g.parentNode.insertBefore(c,g)}(window,document,"script",0,"ga")</script><script>window.onerror=function(){ga("send","exception",{exDescription:function(e,r,n,a,c){var l;e=e.replace(/^Error: /,""),l=c?c.stack.replace(/^Error: /,"").replace(e+"\n","").replace(/^ +/gm,"").replace(/^at /gm,"").replace(/(?: \(|@)http.+\/([^/)]+)\)?(?:\n|$)/gm,"@$1\n").replace(/ *\(eval code(:\d+:\d+)\)(?:\n|$)/gm,"@???$1\n"):r+":"+(n=n||"?")+":"+(a=a||"?");return(e+"\n"+l).substr(0,150)}.apply(null,arguments),exFatal:!0})}</script><link rel="stylesheet" href="styles.4adbe52ad34df01b5273.css"><style>.cdk-high-contrast-active .mat-toolbar{outline:solid 1px}.mat-toolbar-row,.mat-toolbar-single-row{display:flex;box-sizing:border-box;padding:0 16px;width:100%;flex-direction:row;align-items:center;white-space:nowrap}.mat-toolbar-multiple-rows{display:flex;box-sizing:border-box;flex-direction:column;width:100%}.mat-toolbar-multiple-rows{min-height:64px}.mat-toolbar-row,.mat-toolbar-single-row{height:64px}@media(max-width:599px){.mat-toolbar-multiple-rows{min-height:56px}.mat-toolbar-row,.mat-toolbar-single-row{height:56px}}</style><style>.mat-icon{background-repeat:no-repeat;display:inline-block;fill:currentColor;height:24px;width:24px}.mat-icon.mat-icon-inline{font-size:inherit;height:inherit;line-height:inherit;width:inherit}[dir=rtl] .mat-icon-rtl-mirror{transform:scale(-1,1)}.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-prefix .mat-icon,.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-suffix .mat-icon{display:block}.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-prefix .mat-icon-button .mat-icon,.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-suffix .mat-icon-button .mat-icon{margin:auto}</style><style>.mat-button .mat-button-focus-overlay,.mat-icon-button .mat-button-focus-overlay{opacity:0}.mat-button:hover .mat-button-focus-overlay,.mat-stroked-button:hover .mat-button-focus-overlay{opacity:.04}@media(hover:none){.mat-button:hover .mat-button-focus-overlay,.mat-stroked-button:hover .mat-button-focus-overlay{opacity:0}}.mat-button,.mat-flat-button,.mat-icon-button,.mat-stroked-button{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:64px;line-height:36px;padding:0 16px;border-radius:4px;overflow:visible}.mat-button::-moz-focus-inner,.mat-flat-button::-moz-focus-inner,.mat-icon-button::-moz-focus-inner,.mat-stroked-button::-moz-focus-inner{border:0}.mat-button[disabled],.mat-flat-button[disabled],.mat-icon-button[disabled],.mat-stroked-button[disabled]{cursor:default}.mat-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-button.cdk-program-focused .mat-button-focus-overlay,.mat-flat-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-flat-button.cdk-program-focused .mat-button-focus-overlay,.mat-icon-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-icon-button.cdk-program-focused .mat-button-focus-overlay,.mat-stroked-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-stroked-button.cdk-program-focused .mat-button-focus-overlay{opacity:.12}.mat-button::-moz-focus-inner,.mat-flat-button::-moz-focus-inner,.mat-icon-button::-moz-focus-inner,.mat-stroked-button::-moz-focus-inner{border:0}.mat-raised-button{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:64px;line-height:36px;padding:0 16px;border-radius:4px;overflow:visible;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1)}.mat-raised-button::-moz-focus-inner{border:0}.mat-raised-button[disabled]{cursor:default}.mat-raised-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-raised-button.cdk-program-focused .mat-button-focus-overlay{opacity:.12}.mat-raised-button::-moz-focus-inner{border:0}._mat-animation-noopable.mat-raised-button{transition:none;animation:none}.mat-stroked-button{border:1px solid currentColor;padding:0 15px;line-height:34px}.mat-stroked-button .mat-button-focus-overlay,.mat-stroked-button .mat-button-ripple.mat-ripple{top:-1px;left:-1px;right:-1px;bottom:-1px}.mat-fab{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:64px;line-height:36px;padding:0 16px;border-radius:4px;overflow:visible;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1);min-width:0;border-radius:50%;width:56px;height:56px;padding:0;flex-shrink:0}.mat-fab::-moz-focus-inner{border:0}.mat-fab[disabled]{cursor:default}.mat-fab.cdk-keyboard-focused .mat-button-focus-overlay,.mat-fab.cdk-program-focused .mat-button-focus-overlay{opacity:.12}.mat-fab::-moz-focus-inner{border:0}._mat-animation-noopable.mat-fab{transition:none;animation:none}.mat-fab .mat-button-wrapper{padding:16px 0;display:inline-block;line-height:24px}.mat-mini-fab{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:64px;line-height:36px;padding:0 16px;border-radius:4px;overflow:visible;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1);min-width:0;border-radius:50%;width:40px;height:40px;padding:0;flex-shrink:0}.mat-mini-fab::-moz-focus-inner{border:0}.mat-mini-fab[disabled]{cursor:default}.mat-mini-fab.cdk-keyboard-focused .mat-button-focus-overlay,.mat-mini-fab.cdk-program-focused .mat-button-focus-overlay{opacity:.12}.mat-mini-fab::-moz-focus-inner{border:0}._mat-animation-noopable.mat-mini-fab{transition:none;animation:none}.mat-mini-fab .mat-button-wrapper{padding:8px 0;display:inline-block;line-height:24px}.mat-icon-button{padding:0;min-width:0;width:40px;height:40px;flex-shrink:0;line-height:40px;border-radius:50%}.mat-icon-button .mat-icon,.mat-icon-button i{line-height:24px}.mat-button-focus-overlay,.mat-button-ripple.mat-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none;border-radius:inherit}.mat-button-ripple.mat-ripple:not(:empty){transform:translateZ(0)}.mat-button-focus-overlay{opacity:0;transition:opacity .2s cubic-bezier(.35,0,.25,1),background-color .2s cubic-bezier(.35,0,.25,1)}._mat-animation-noopable .mat-button-focus-overlay{transition:none}.cdk-high-contrast-active .mat-button-focus-overlay{background-color:#fff}.cdk-high-contrast-black-on-white .mat-button-focus-overlay{background-color:#000}.mat-button-ripple-round{border-radius:50%;z-index:1}.mat-button .mat-button-wrapper>*,.mat-fab .mat-button-wrapper>*,.mat-flat-button .mat-button-wrapper>*,.mat-icon-button .mat-button-wrapper>*,.mat-mini-fab .mat-button-wrapper>*,.mat-raised-button .mat-button-wrapper>*,.mat-stroked-button .mat-button-wrapper>*{vertical-align:middle}.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-prefix .mat-icon-button,.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-suffix .mat-icon-button{display:block;font-size:inherit;width:2.5em;height:2.5em}.cdk-high-contrast-active .mat-button,.cdk-high-contrast-active .mat-fab,.cdk-high-contrast-active .mat-flat-button,.cdk-high-contrast-active .mat-icon-button,.cdk-high-contrast-active .mat-mini-fab,.cdk-high-contrast-active .mat-raised-button{outline:solid 1px}</style><style>.mat-drawer-container{position:relative;z-index:1;box-sizing:border-box;-webkit-overflow-scrolling:touch;display:block;overflow:hidden}.mat-drawer-container[fullscreen]{top:0;left:0;right:0;bottom:0;position:absolute}.mat-drawer-container[fullscreen].mat-drawer-container-has-open{overflow:hidden}.mat-drawer-container.mat-drawer-container-explicit-backdrop .mat-drawer-side{z-index:3}.mat-drawer-container.ng-animate-disabled .mat-drawer-backdrop,.mat-drawer-container.ng-animate-disabled .mat-drawer-content,.ng-animate-disabled .mat-drawer-container .mat-drawer-backdrop,.ng-animate-disabled .mat-drawer-container .mat-drawer-content{transition:none}.mat-drawer-backdrop{top:0;left:0;right:0;bottom:0;position:absolute;display:block;z-index:3;visibility:hidden}.mat-drawer-backdrop.mat-drawer-shown{visibility:visible}.mat-drawer-transition .mat-drawer-backdrop{transition-duration:.4s;transition-timing-function:cubic-bezier(.25,.8,.25,1);transition-property:background-color,visibility}.cdk-high-contrast-active .mat-drawer-backdrop{opacity:.5}.mat-drawer-content{position:relative;z-index:1;display:block;height:100%;overflow:auto}.mat-drawer-transition .mat-drawer-content{transition-duration:.4s;transition-timing-function:cubic-bezier(.25,.8,.25,1);transition-property:transform,margin-left,margin-right}.mat-drawer{position:relative;z-index:4;display:block;position:absolute;top:0;bottom:0;z-index:3;outline:0;box-sizing:border-box;overflow-y:auto;transform:translate3d(-100%,0,0)}.cdk-high-contrast-active .mat-drawer,.cdk-high-contrast-active [dir=rtl] .mat-drawer.mat-drawer-end{border-right:solid 1px currentColor}.cdk-high-contrast-active .mat-drawer.mat-drawer-end,.cdk-high-contrast-active [dir=rtl] .mat-drawer{border-left:solid 1px currentColor;border-right:none}.mat-drawer.mat-drawer-side{z-index:2}.mat-drawer.mat-drawer-end{right:0;transform:translate3d(100%,0,0)}[dir=rtl] .mat-drawer{transform:translate3d(100%,0,0)}[dir=rtl] .mat-drawer.mat-drawer-end{left:0;right:auto;transform:translate3d(-100%,0,0)}.mat-drawer-inner-container{width:100%;height:100%;overflow:auto;-webkit-overflow-scrolling:touch}.mat-sidenav-fixed{position:fixed}</style><style>.nav-link.highlight[_ngcontent-ng-docs-c30]{color:#ff0}</style><style>.mat-progress-bar{display:block;height:4px;overflow:hidden;position:relative;transition:opacity 250ms linear;width:100%}._mat-animation-noopable.mat-progress-bar{transition:none;animation:none}.mat-progress-bar .mat-progress-bar-element,.mat-progress-bar .mat-progress-bar-fill::after{height:100%;position:absolute;width:100%}.mat-progress-bar .mat-progress-bar-background{width:calc(100% + 10px)}.cdk-high-contrast-active .mat-progress-bar .mat-progress-bar-background{display:none}.mat-progress-bar .mat-progress-bar-buffer{transform-origin:top left;transition:transform 250ms ease}.cdk-high-contrast-active .mat-progress-bar .mat-progress-bar-buffer{border-top:solid 5px;opacity:.5}.mat-progress-bar .mat-progress-bar-secondary{display:none}.mat-progress-bar .mat-progress-bar-fill{animation:none;transform-origin:top left;transition:transform 250ms ease}.cdk-high-contrast-active .mat-progress-bar .mat-progress-bar-fill{border-top:solid 4px}.mat-progress-bar .mat-progress-bar-fill::after{animation:none;content:"";display:inline-block;left:0}.mat-progress-bar[dir=rtl],[dir=rtl] .mat-progress-bar{transform:rotateY(180deg)}.mat-progress-bar[mode=query]{transform:rotateZ(180deg)}.mat-progress-bar[mode=query][dir=rtl],[dir=rtl] .mat-progress-bar[mode=query]{transform:rotateZ(180deg) rotateY(180deg)}.mat-progress-bar[mode=indeterminate] .mat-progress-bar-fill,.mat-progress-bar[mode=query] .mat-progress-bar-fill{transition:none}.mat-progress-bar[mode=indeterminate] .mat-progress-bar-primary,.mat-progress-bar[mode=query] .mat-progress-bar-primary{-webkit-backface-visibility:hidden;backface-visibility:hidden;animation:mat-progress-bar-primary-indeterminate-translate 2s infinite linear;left:-145.166611%}.mat-progress-bar[mode=indeterminate] .mat-progress-bar-primary.mat-progress-bar-fill::after,.mat-progress-bar[mode=query] .mat-progress-bar-primary.mat-progress-bar-fill::after{-webkit-backface-visibility:hidden;backface-visibility:hidden;animation:mat-progress-bar-primary-indeterminate-scale 2s infinite linear}.mat-progress-bar[mode=indeterminate] .mat-progress-bar-secondary,.mat-progress-bar[mode=query] .mat-progress-bar-secondary{-webkit-backface-visibility:hidden;backface-visibility:hidden;animation:mat-progress-bar-secondary-indeterminate-translate 2s infinite linear;left:-54.888891%;display:block}.mat-progress-bar[mode=indeterminate] .mat-progress-bar-secondary.mat-progress-bar-fill::after,.mat-progress-bar[mode=query] .mat-progress-bar-secondary.mat-progress-bar-fill::after{-webkit-backface-visibility:hidden;backface-visibility:hidden;animation:mat-progress-bar-secondary-indeterminate-scale 2s infinite linear}.mat-progress-bar[mode=buffer] .mat-progress-bar-background{-webkit-backface-visibility:hidden;backface-visibility:hidden;animation:mat-progress-bar-background-scroll 250ms infinite linear;display:block}.mat-progress-bar._mat-animation-noopable .mat-progress-bar-background,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-buffer,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-fill,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-fill::after,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-primary,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-primary.mat-progress-bar-fill::after,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-secondary,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-secondary.mat-progress-bar-fill::after{animation:none;transition:none}@keyframes mat-progress-bar-primary-indeterminate-translate{0%{transform:translateX(0)}20%{animation-timing-function:cubic-bezier(.5,0,.701732,.495819);transform:translateX(0)}59.15%{animation-timing-function:cubic-bezier(.302435,.381352,.55,.956352);transform:translateX(83.67142%)}100%{transform:translateX(200.611057%)}}@keyframes mat-progress-bar-primary-indeterminate-scale{0%{transform:scaleX(.08)}36.65%{animation-timing-function:cubic-bezier(.334731,.12482,.785844,1);transform:scaleX(.08)}69.15%{animation-timing-function:cubic-bezier(.06,.11,.6,1);transform:scaleX(.661479)}100%{transform:scaleX(.08)}}@keyframes mat-progress-bar-secondary-indeterminate-translate{0%{animation-timing-function:cubic-bezier(.15,0,.515058,.409685);transform:translateX(0)}25%{animation-timing-function:cubic-bezier(.31033,.284058,.8,.733712);transform:translateX(37.651913%)}48.35%{animation-timing-function:cubic-bezier(.4,.627035,.6,.902026);transform:translateX(84.386165%)}100%{transform:translateX(160.277782%)}}@keyframes mat-progress-bar-secondary-indeterminate-scale{0%{animation-timing-function:cubic-bezier(.15,0,.515058,.409685);transform:scaleX(.08)}19.15%{animation-timing-function:cubic-bezier(.31033,.284058,.8,.733712);transform:scaleX(.457104)}44.15%{animation-timing-function:cubic-bezier(.4,.627035,.6,.902026);transform:scaleX(.72796)}100%{transform:scaleX(.08)}}@keyframes mat-progress-bar-background-scroll{to{transform:translateX(-8px)}}</style><script charset="utf-8" src="toc-toc-module-es2015.f8531f591ee147aebcc6.js"></script><script charset="utf-8" src="default~code-code-example-module~code-code-tabs-module-es2015.9efcc76d2979a2e605e0.js"></script><script charset="utf-8" src="code-code-example-module-es2015.fa05e6f700453813d256.js"></script><script charset="utf-8" src="code-code-tabs-module-es2015.505e1e0a869946918011.js"></script><script charset="utf-8" src="live-example-live-example-module-es2015.a8023d1b084857ef476b.js"></script><script charset="utf-8" src="assets-js-prettify-js-es2015.ba856648f2dd2d930a9b.js"></script><style>.mat-card{transition:box-shadow 280ms cubic-bezier(.4,0,.2,1);display:block;position:relative;padding:16px;border-radius:4px}._mat-animation-noopable.mat-card{transition:none;animation:none}.mat-card .mat-divider-horizontal{position:absolute;left:0;width:100%}[dir=rtl] .mat-card .mat-divider-horizontal{left:auto;right:0}.mat-card .mat-divider-horizontal.mat-divider-inset{position:static;margin:0}[dir=rtl] .mat-card .mat-divider-horizontal.mat-divider-inset{margin-right:0}.cdk-high-contrast-active .mat-card{outline:solid 1px}.mat-card-actions,.mat-card-content,.mat-card-subtitle{display:block;margin-bottom:16px}.mat-card-title{display:block;margin-bottom:8px}.mat-card-actions{margin-left:-8px;margin-right:-8px;padding:8px 0}.mat-card-actions-align-end{display:flex;justify-content:flex-end}.mat-card-image{width:calc(100% + 32px);margin:0 -16px 16px -16px}.mat-card-footer{display:block;margin:0 -16px -16px -16px}.mat-card-actions .mat-button,.mat-card-actions .mat-raised-button,.mat-card-actions .mat-stroked-button{margin:0 8px}.mat-card-header{display:flex;flex-direction:row}.mat-card-header .mat-card-title{margin-bottom:12px}.mat-card-header-text{margin:0 16px}.mat-card-avatar{height:40px;width:40px;border-radius:50%;flex-shrink:0;object-fit:cover}.mat-card-title-group{display:flex;justify-content:space-between}.mat-card-sm-image{width:80px;height:80px}.mat-card-md-image{width:112px;height:112px}.mat-card-lg-image{width:152px;height:152px}.mat-card-xl-image{width:240px;height:240px;margin:-8px}.mat-card-title-group>.mat-card-xl-image{margin:-8px 0 8px}@media(max-width:599px){.mat-card-title-group{margin:0}.mat-card-xl-image{margin-left:0;margin-right:0}}.mat-card-content>:first-child,.mat-card>:first-child{margin-top:0}.mat-card-content>:last-child:not(.mat-card-footer),.mat-card>:last-child:not(.mat-card-footer){margin-bottom:0}.mat-card-image:first-child{margin-top:-16px;border-top-left-radius:inherit;border-top-right-radius:inherit}.mat-card>.mat-card-actions:last-child{margin-bottom:-8px;padding-bottom:0}.mat-card-actions .mat-button:first-child,.mat-card-actions .mat-raised-button:first-child,.mat-card-actions .mat-stroked-button:first-child{margin-left:0;margin-right:0}.mat-card-subtitle:not(:first-child),.mat-card-title:not(:first-child){margin-top:-4px}.mat-card-header .mat-card-subtitle:not(:first-child){margin-top:-8px}.mat-card>.mat-card-xl-image:first-child{margin-top:-8px}.mat-card>.mat-card-xl-image:last-child{margin-bottom:-8px}</style><style>.mat-tab-group{display:flex;flex-direction:column}.mat-tab-group.mat-tab-group-inverted-header{flex-direction:column-reverse}.mat-tab-label{height:48px;padding:0 24px;cursor:pointer;box-sizing:border-box;opacity:.6;min-width:160px;text-align:center;display:inline-flex;justify-content:center;align-items:center;white-space:nowrap;position:relative}.mat-tab-label:focus{outline:0}.mat-tab-label:focus:not(.mat-tab-disabled){opacity:1}.cdk-high-contrast-active .mat-tab-label:focus{outline:dotted 2px}.mat-tab-label.mat-tab-disabled{cursor:default}.cdk-high-contrast-active .mat-tab-label.mat-tab-disabled{opacity:.5}.mat-tab-label .mat-tab-label-content{display:inline-flex;justify-content:center;align-items:center;white-space:nowrap}.cdk-high-contrast-active .mat-tab-label{opacity:1}@media(max-width:599px){.mat-tab-label{padding:0 12px}}@media(max-width:959px){.mat-tab-label{padding:0 12px}}.mat-tab-group[mat-stretch-tabs]>.mat-tab-header .mat-tab-label{flex-basis:0;flex-grow:1}.mat-tab-body-wrapper{position:relative;overflow:hidden;display:flex;transition:height .5s cubic-bezier(.35,0,.25,1)}._mat-animation-noopable.mat-tab-body-wrapper{transition:none;animation:none}.mat-tab-body{top:0;left:0;right:0;bottom:0;position:absolute;display:block;overflow:hidden;flex-basis:100%}.mat-tab-body.mat-tab-body-active{position:relative;overflow-x:hidden;overflow-y:auto;z-index:1;flex-grow:1}.mat-tab-group.mat-tab-group-dynamic-height .mat-tab-body.mat-tab-body-active{overflow-y:hidden}</style><style>.mat-tab-header{display:flex;overflow:hidden;position:relative;flex-shrink:0}.mat-tab-header-pagination{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;position:relative;display:none;justify-content:center;align-items:center;min-width:32px;cursor:pointer;z-index:2;-webkit-tap-highlight-color:transparent;touch-action:none}.mat-tab-header-pagination-controls-enabled .mat-tab-header-pagination{display:flex}.mat-tab-header-pagination-before,.mat-tab-header-rtl .mat-tab-header-pagination-after{padding-left:4px}.mat-tab-header-pagination-before .mat-tab-header-pagination-chevron,.mat-tab-header-rtl .mat-tab-header-pagination-after .mat-tab-header-pagination-chevron{transform:rotate(-135deg)}.mat-tab-header-pagination-after,.mat-tab-header-rtl .mat-tab-header-pagination-before{padding-right:4px}.mat-tab-header-pagination-after .mat-tab-header-pagination-chevron,.mat-tab-header-rtl .mat-tab-header-pagination-before .mat-tab-header-pagination-chevron{transform:rotate(45deg)}.mat-tab-header-pagination-chevron{border-style:solid;border-width:2px 2px 0 0;content:"";height:8px;width:8px}.mat-tab-header-pagination-disabled{box-shadow:none;cursor:default}.mat-tab-list{flex-grow:1;position:relative;transition:transform .5s cubic-bezier(.35,0,.25,1)}.mat-ink-bar{position:absolute;bottom:0;height:2px;transition:.5s cubic-bezier(.35,0,.25,1)}._mat-animation-noopable.mat-ink-bar{transition:none;animation:none}.mat-tab-group-inverted-header .mat-ink-bar{bottom:auto;top:0}.cdk-high-contrast-active .mat-ink-bar{outline:solid 2px;height:0}.mat-tab-labels{display:flex}[mat-align-tabs=center] .mat-tab-labels{justify-content:center}[mat-align-tabs=end] .mat-tab-labels{justify-content:flex-end}.mat-tab-label-container{display:flex;flex-grow:1;overflow:hidden;z-index:1}._mat-animation-noopable.mat-tab-list{transition:none;animation:none}.mat-tab-label{height:48px;padding:0 24px;cursor:pointer;box-sizing:border-box;opacity:.6;min-width:160px;text-align:center;display:inline-flex;justify-content:center;align-items:center;white-space:nowrap;position:relative}.mat-tab-label:focus{outline:0}.mat-tab-label:focus:not(.mat-tab-disabled){opacity:1}.cdk-high-contrast-active .mat-tab-label:focus{outline:dotted 2px}.mat-tab-label.mat-tab-disabled{cursor:default}.cdk-high-contrast-active .mat-tab-label.mat-tab-disabled{opacity:.5}.mat-tab-label .mat-tab-label-content{display:inline-flex;justify-content:center;align-items:center;white-space:nowrap}.cdk-high-contrast-active .mat-tab-label{opacity:1}@media(max-width:599px){.mat-tab-label{min-width:72px}}</style><style>.mat-tab-body-content{height:100%;overflow:auto}.mat-tab-group-dynamic-height .mat-tab-body-content{overflow:hidden}</style></head><body><aio-shell ng-version="9.0.0-rc.11" class="aio-notification-hide folder-guide mode-stable page-guide-testing sidenav-open view-SideNav"><div id="top-of-page"></div><mat-toolbar color="primary" class="mat-toolbar app-toolbar no-print mat-primary mat-toolbar-multiple-rows"><mat-toolbar-row class="mat-toolbar-row notification-container"><aio-notification notificationid="survey-february-2019" expirationdate="2019-03-01" class="ng-tns-c22-0 ng-trigger ng-trigger-hideAnimation" style="height:0"><span class="content ng-tns-c22-0"><a href="http://bit.ly/angular-survey-2019" target="_blank" class="ng-tns-c22-0"><mat-icon role="img" svgicon="insert_comment" aria-label="Announcement" class="mat-icon notranslate icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg></mat-icon><span class="message"><b>填写这份《一分钟调查》</b>，帮我们（开发组）做得更好！</span><span class="action-button">去填写</span></a></span><button mat-icon-button="" aria-label="Close" class="close-button ng-tns-c22-0 mat-icon-button mat-button-base"><span class="mat-button-wrapper"><mat-icon role="img" svgicon="close" aria-label="Dismiss notification" class="mat-icon notranslate mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg></mat-icon></span><div matripple="" class="mat-ripple mat-button-ripple mat-button-ripple-round"></div><div class="mat-button-focus-overlay"></div></button></aio-notification></mat-toolbar-row><mat-toolbar-row class="mat-toolbar-row"><button mat-button="" title="Docs menu" class="hamburger mat-button mat-button-base"><span class="mat-button-wrapper"><mat-icon role="img" svgicon="menu" class="mat-icon notranslate mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"></path></svg></mat-icon></span><div matripple="" class="mat-ripple mat-button-ripple"></div><div class="mat-button-focus-overlay"></div></button><a href="/" class="nav-link home"><img src="assets/images/logos/angular/logo-nav@2x.png" width="150" height="40" title="Home" alt="Home" class="ng-star-inserted"></a><aio-top-menu _nghost-ng-docs-c30="" class="ng-star-inserted"><ul _ngcontent-ng-docs-c30="" role="navigation"><li _ngcontent-ng-docs-c30="" class="ng-star-inserted"><a _ngcontent-ng-docs-c30="" class="nav-link" href="features" title="特性"><span _ngcontent-ng-docs-c30="" class="nav-link-inner">特性</span></a></li><li _ngcontent-ng-docs-c30="" class="ng-star-inserted"><a _ngcontent-ng-docs-c30="" class="nav-link" href="docs" title="文档"><span _ngcontent-ng-docs-c30="" class="nav-link-inner">文档</span></a></li><li _ngcontent-ng-docs-c30="" class="ng-star-inserted"><a _ngcontent-ng-docs-c30="" class="nav-link" href="resources" title="资源"><span _ngcontent-ng-docs-c30="" class="nav-link-inner">资源</span></a></li><li _ngcontent-ng-docs-c30="" class="ng-star-inserted"><a _ngcontent-ng-docs-c30="" class="nav-link" href="events" title="会议"><span _ngcontent-ng-docs-c30="" class="nav-link-inner">会议</span></a></li><li _ngcontent-ng-docs-c30="" class="ng-star-inserted"><a _ngcontent-ng-docs-c30="" class="nav-link" href="https://blog.angular.io/" title="博客"><span _ngcontent-ng-docs-c30="" class="nav-link-inner">博客</span></a></li><li _ngcontent-ng-docs-c30="" class="ng-star-inserted"><a _ngcontent-ng-docs-c30="" class="nav-link" href="translations/cn/home" title="关于中文版"><span _ngcontent-ng-docs-c30="" class="nav-link-inner">关于中文版</span></a></li></ul></aio-top-menu><aio-search-box class="search-container"><input type="search" aria-label="search" placeholder="搜索"></aio-search-box><div class="toolbar-external-icons-container"><a href="https://twitter.com/angular" title="Twitter" aria-label="Angular on twitter"><mat-icon role="img" svgicon="logos:twitter" class="mat-icon notranslate mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 50 59" xmlns="http://www.w3.org/2000/svg"><path d="M50,9.3c-1.8,0.8-3.8,1.4-5.9,1.6c2.1-1.3,3.7-3.3,4.5-5.7c-2,1.2-4.2,2-6.5,2.5c-1.9-2-4.5-3.2-7.5-3.2c-5.7,0-10.3,4.6-10.3,10.3c0,0.8,0.1,1.6,0.3,2.3C16.1,16.7,8.5,12.6,3.5,6.4c-0.9,1.5-1.4,3.3-1.4,5.2c0,3.6,1.8,6.7,4.6,8.5C5,20,3.4,19.6,2,18.8c0,0,0,0.1,0,0.1c0,5,3.5,9.1,8.2,10.1c-0.9,0.2-1.8,0.4-2.7,0.4c-0.7,0-1.3-0.1-1.9-0.2c1.3,4.1,5.1,7,9.6,7.1c-3.5,2.8-7.9,4.4-12.7,4.4c-0.8,0-1.6,0-2.4-0.1c4.5,2.9,9.9,4.6,15.7,4.6c18.9,0,29.2-15.6,29.2-29.2c0-0.4,0-0.9,0-1.3C46.9,13.2,48.6,11.4,50,9.3z"></path></svg></mat-icon></a><a href="https://github.com/angular/angular" title="GitHub" aria-label="Angular on github"><mat-icon role="img" svgicon="logos:github" class="mat-icon notranslate mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 51.8 50.4" xmlns="http://www.w3.org/2000/svg"><path d="M25.9,0.2C11.8,0.2,0.3,11.7,0.3,25.8c0,11.3,7.3,20.9,17.5,24.3c1.3,0.2,1.7-0.6,1.7-1.2c0-0.6,0-2.6,0-4.8c-7.1,1.5-8.6-3-8.6-3c-1.2-3-2.8-3.7-2.8-3.7c-2.3-1.6,0.2-1.6,0.2-1.6c2.6,0.2,3.9,2.6,3.9,2.6c2.3,3.9,6,2.8,7.5,2.1c0.2-1.7,0.9-2.8,1.6-3.4c-5.7-0.6-11.7-2.8-11.7-12.7c0-2.8,1-5.1,2.6-6.9c-0.3-0.7-1.1-3.3,0.3-6.8c0,0,2.1-0.7,7,2.6c2-0.6,4.2-0.9,6.4-0.9c2.2,0,4.4,0.3,6.4,0.9c4.9-3.3,7-2.6,7-2.6c1.4,3.5,0.5,6.1,0.3,6.8c1.6,1.8,2.6,4.1,2.6,6.9c0,9.8-6,12-11.7,12.6c0.9,0.8,1.7,2.4,1.7,4.7c0,3.4,0,6.2,0,7c0,0.7,0.5,1.5,1.8,1.2c10.2-3.4,17.5-13,17.5-24.3C51.5,11.7,40.1,0.2,25.9,0.2z"></path></svg></mat-icon></a></div></mat-toolbar-row></mat-toolbar><mat-sidenav-container role="main" class="mat-drawer-container mat-sidenav-container sidenav-container mat-drawer-transition has-floating-toc"><div class="mat-drawer-backdrop ng-star-inserted"></div><div class="cdk-visually-hidden cdk-focus-trap-anchor" aria-hidden="true"></div><mat-sidenav tabindex="-1" class="mat-drawer mat-sidenav sidenav ng-tns-c18-1 ng-trigger ng-trigger-transform mat-drawer-side ng-star-inserted mat-drawer-opened" style="transform:none;visibility:visible"><div class="mat-drawer-inner-container ng-tns-c18-1"><aio-nav-menu class="ng-tns-c18-1"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="docs" title="Angular 文档简介" target="_self"><span>简介</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-1 collapsed ng-star-inserted" title="通过构建第一个 Angular 应用来学习基础知识" aria-pressed="false"><span>快速上手</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="start" title="介绍 Angular 的组件模型、模板语法和组件通讯" target="_self"><span>你的第一个应用</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="start/routing" title="介绍如何使用浏览器的 URL 在组件之间进行路由" target="_self"><span>路由</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="start/data" title="介绍服务以及如何访问外部数据" target="_self"><span>管理数据</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="start/forms" title="学习如何使用表单从用户那里获取并管理数据" target="_self"><span>表单</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="start/deployment" title="通过你的应用放到 Firebase 或自己的服务器上来把它分享给外界" target="_self"><span>部署</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="guide/setup-local" title="使用 Angular CLI 搭建本地开发环境简介" target="_self"><span>搭建环境</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-1 collapsed ng-star-inserted" title="Angular 的基本原理" aria-pressed="false"><span>基本原理</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="介绍 Angular 应用中的一些基本概念。" aria-pressed="false"><span>Angular 的基本概念</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/architecture" title="Angular 应用中的基本构造块。" target="_self"><span>基本概念简介</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/architecture-modules" title="关于 Angular 模块（NgModules）。" target="_self"><span>模块简介</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/architecture-components" title="关于组件、模板和视图。" target="_self"><span>组件简介</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/architecture-services" title="关于服务与依赖注入。" target="_self"><span>服务与 DI 简介</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/architecture-next-steps" title="超越基础阶段。" target="_self"><span>后续步骤</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="英雄指南是这里大量 Angular 范例的基础" aria-pressed="false"><span>英雄指南</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="tutorial" title="《英雄指南》教程简介" target="_self"><span>简介</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt0" title="创建应用的外壳" target="_self"><span>应用的“外壳”</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt1" title="第一部分：构建一个简单的英雄编辑器" target="_self"><span>1. 英雄编辑器</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt2" title="第二部分：构建一个主从结构的页面，用于展现英雄列表。" target="_self"><span>2. 显示英雄列表</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt3" title="第三部分：把主从结构的视图重构成几个独立的组件。" target="_self"><span>3. 创建特性组件</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt4" title="第四部分：创建一个可复用的服务来管理英雄数据。" target="_self"><span>4. 添加服务</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt5" title="第五部分：添加 Angular 路由器，并且学习在视图之间导航。" target="_self"><span>5. 添加应用内导航</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt6" title="第六部分：通过 HTTP 来获取并保存英雄数据。" target="_self"><span>6. 从服务器获取数据</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="通过数据绑定构建动态视图" aria-pressed="false"><span>组件与模板</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/displaying-data" title="属性绑定可以帮助应用把数据显示在界面上" target="_self"><span>显示数据</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/template-syntax" title="学习如何写模板，以便借助数据绑定机制显示数据并响应事件。" target="_self"><span>模板语法</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/user-input" title="用户输入会触发 DOM 事件。Angular 会通过事件绑定来监听那些事件，并把修改后的值传回应用的组件和模型中。" target="_self"><span>用户输入</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/lifecycle-hooks" title="Angular 调用指令和组件的生命周期钩子函数，包括它的创建、变更和销毁时。" target="_self"><span>生命周期钩子</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/component-interaction" title="在不同的指令和组件之间共享信息" target="_self"><span>组件交互</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/component-styles" title="添加专属于某个组件的样式" target="_self"><span>组件样式</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dynamic-component-loader" title="动态加载组件" target="_self"><span>动态组件</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/elements" title="把组件转换成自定义元素" target="_self"><span>Angular 元素</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/attribute-directives" title="属性型指令把行为添加到现有元素上。" target="_self"><span>属性型指令</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/structural-directives" title="结构型指令可以操纵页面的布局" target="_self"><span>结构型指令</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/pipes" title="管道可以在模板中转换显示的内容。" target="_self"><span>管道</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="Angular 的表单" aria-pressed="false"><span>表单</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/forms-overview" title="表单可以创建集中、高效、引人注目的输入体验。Angular 表单可以协调一组数据绑定控件，跟踪变更，验证输入，并表达错误信息。" target="_self"><span>简介</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/reactive-forms" title="使用 FormBuilder、表单组和表单数组创建响应式表单。" target="_self"><span>响应式表单</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/forms" title="使用指令和 Angular 模板语法创建模板驱动表单。" target="_self"><span>模板驱动表单</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/form-validation" title="验证用户的表单输入" target="_self"><span>表单验证</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dynamic-form" title="使用 FormGroup 渲染动态表单。" target="_self"><span>动态表单</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="Observable 与 RxJS" aria-pressed="false"><span>Observable 与 RxJS</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/observables" title="" target="_self"><span>可观察对象(Observable)</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/rx-library" title="" target="_self"><span>RxJS 库</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/observables-in-angular" title="" target="_self"><span>Angular 中的可观察对象</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/practical-observable-usage" title="" target="_self"><span>用法实战</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/comparing-observables" title="" target="_self"><span>与其它技术的比较</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="Angular 中的模块" aria-pressed="false"><span>NgModules</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/ngmodules" title="使用 NgModule 让你的应用更高效" target="_self"><span>NgModule 简介</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/ngmodule-vs-jsmodule" title="JavaScript 模块和 NgModule 之间的差异" target="_self"><span>JS 模块 vs NgModule</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/bootstrapping" title="告诉 Angular 如何在根 &quot;AppModule&quot; 中构造和引导应用。" target="_self"><span>应用的根模块</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/frequent-ngmodules" title="介绍最常用的 NgModule" target="_self"><span>常用模块</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/module-types" title="介绍特性模块的几种类型" target="_self"><span>特性模块的分类</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/entry-components" title="关于 Angular 中入口组件的一切" target="_self"><span>入口组件</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/feature-modules" title="创建特性模块，以组织你的代码" target="_self"><span>特性模块</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/providers" title="服务提供商与 NgModule" target="_self"><span>服务提供商</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/singleton-services" title="创建单例服务" target="_self"><span>单例服务</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/lazy-loading-ngmodules" title="惰性加载模块，以提高应用的性能" target="_self"><span>惰性加载的特性模块</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/sharing-ngmodules" title="共享 NgModule 让你的应用现代化。" target="_self"><span>共享 NgModule</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/ngmodule-api" title="理解 NgModule 的那些细节。" target="_self"><span>NgModule API</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/ngmodule-faq" title="回答关于 NgModules 的常见问题。" target="_self"><span>NgModule 常见问题</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="依赖注入：创建并注入各种服务。" aria-pressed="false"><span>依赖注入</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dependency-injection" title="Angular 的依赖注入系统能够为 Angular 创建的类创建并交付它们所依赖的服务。" target="_self"><span>Angular 依赖注入</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/hierarchical-dependency-injection" title="与组件树平行的注入器树，并支持嵌套的依赖。" target="_self"><span>多级注入器</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dependency-injection-providers" title="各种提供商类型的更多知识。" target="_self"><span>DI 提供商</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dependency-injection-in-action" title="依赖注入的使用技巧" target="_self"><span>DI 实战</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dependency-injection-navtree" title="使用注入器树来查找父组件。" target="_self"><span>浏览组件树</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/http" title="通过 HTTP 协议与远程服务器对话。" target="_self"><span>HttpClient</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/router" title="揭示如何通过 Angular 路由进行基本的屏幕导航。" target="_self"><span>路由与导航</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="Angular 动画系统指南" aria-pressed="false"><span>动画</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/animations" title="Angular 动画的基础技术。" target="_self"><span>简介</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/transition-and-triggers" title="转场与触发器的高级技术。" target="_self"><span>转场与触发器</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/complex-animation-sequences" title="复杂的 Angular 动画序列。" target="_self"><span>复杂序列</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/reusable-animations" title="创建可复用的动画。" target="_self"><span>可复用动画</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/route-animations" title="为路由提供转场动画。" target="_self"><span>路由转场动画</span></a></div></aio-nav-item></div></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-1 collapsed ng-star-inserted" title="把 Angular 用到你的实际工作中的一些技巧" aria-pressed="false"><span>其它技术</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/security" title="Angular 应用开发中的安全技术。" target="_self"><span>安全</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/i18n" title="把应用模板中的文本翻译成多种语言。" target="_self"><span>国际化（i18n）</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/accessibility" title="设计能被所有用户访问的应用" target="_self"><span>无障碍（a11y）</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="Angular Service Worker: 控制应用资源的缓存。" aria-pressed="false"><span>Service Worker 与 PWA</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/service-worker-intro" title="Angular 对 Service Worker 的实现提升了慢速或不稳定的网络连接下的用户体验。" target="_self"><span>简介</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/service-worker-getting-started" title="在 CLI 项目中启用 Service Worker，并在浏览器中查看效果。" target="_self"><span>快速上手</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/app-shell" title="在 CLI 项目中启用应用外壳。" target="_self"><span>应用外壳</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/service-worker-communications" title="那些能让你和 Angular 的 Service Worker 通讯的服务类。" target="_self"><span>与 Service Worker 通讯</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/service-worker-devops" title="使用 Service Worker 运行应用、管理应用更新、调试以及杀掉正在运行的应用。" target="_self"><span>生产环境下的 Service Worker</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/service-worker-config" title="配置 Service Worker 的缓存行为。" target="_self"><span>Service Worker 配置</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/universal" title="使用 Angular Universal 在服务端渲染 HTML。" target="_self"><span>服务端渲染</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="把 AngularJS 应用增量式的升级到 Angular。" aria-pressed="false"><span>从 AngularJS 升级</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/upgrade" title="把 AngularJS 应用增量式的升级到 Angular。" target="_self"><span>升级步骤</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/upgrade-performance" title="用更灵活的方式把 AngularJS 升级到 Angular。" target="_self"><span>更关注性能的升级方式</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/ajs-quick-reference" title="学习如何把 AngularJS 的概念映射到 Angular 中。" target="_self"><span>AngularJS 与 Angular 的概念对照</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="使用共享库扩展 Angular" aria-pressed="false"><span>开发 Angular 库</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/libraries" title="理解何时以及如何使用和创建库。" target="_self"><span>库概览</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/using-libraries" title="把已发布的库集成进你的应用中。" target="_self"><span>使用已发布的库</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/creating-libraries" title="通过创建、发布和使用你自己的库来扩展 Angular。" target="_self"><span>创建库</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="理解原理图" aria-pressed="false"><span>原理图（Schematic）</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/schematics" title="理解 Angular 如何使用原理图。" target="_self"><span>原理图概览</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/schematics-authoring" title="理解原理图的结构。" target="_self"><span>制作原理图</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/schematics-for-libraries" title="使用原理图来把你的库集成进 Angular CLI 中。" target="_self"><span>库的原理图</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/cli-builder" title="使用构建器定制 Angular CLI。" target="_self"><span>CLI 构建器</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/web-worker" title="在 Angular CLI 中使用 Web Worker。" target="_self"><span>Web Worker</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-1 expanded selected ng-star-inserted" title="关于构建、测试和部署的信息" aria-pressed="true"><span>开发工作流</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 expanded selected"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="理解 AOT 预先编译器。" aria-pressed="false"><span>AOT 预先编译器</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/aot-compiler" title="学习为何以及如何使用预先编译器。" target="_self"><span>预先编译</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/angular-compiler-options" title="配置 AOT 编译。" target="_self"><span>Angular 编译器选项</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/aot-metadata-errors" title="解决 AOT 编译错误。" target="_self"><span>AOT 元数据错误</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/template-typecheck" title="Angular 中的模板类型检查。" target="_self"><span>模板类型检查</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/build" title="构建应用及为应用启动开发服务器。" target="_self"><span>构建与运行</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/bazel" title="如何配置你的环境，以利用 Bazel 进行构建和测试。" target="_self"><span>使用 Bazel 进行构建</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 expanded selected ng-star-inserted" style="position:relative" href="guide/testing" title="测试 Angular 应用的技巧与实践。" target="_self"><span>测试</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/deployment" title="了解如何部署 Angular 应用。" target="_self"><span>发布</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-2 collapsed ng-star-inserted" title="与开发环境和工具集成起来" aria-pressed="false"><span>开发工具集成</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/language-service" title="使用 Angular 语言服务加速开发。" target="_self"><span>语言服务</span></a></div></aio-nav-item></div></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-1 collapsed ng-star-inserted" title="工作空间与项目的结构，及其配置文件。" aria-pressed="false"><span>配置</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/file-structure" title="Angular 工作区在文件系统中是怎样的。" target="_self"><span>项目文件结构</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/workspace-config" title="&quot;angular.json&quot; 包含供 CLI 命令使用的工作区和项目默认配置。" target="_self"><span>工作区配置</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/npm-packages" title="开发期间和运行期间所需的 npm 包的说明。" target="_self"><span>npm 包</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/typescript-configuration" title="给 Angular 开发者的 TypeScript 配置。" target="_self"><span>TypeScript 配置</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/browser-support" title="浏览器支持与腻子脚本指南。" target="_self"><span>浏览器支持</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-1 collapsed ng-star-inserted" title="Angular 的版本发布实践、更新与升级。" aria-pressed="false"><span>发布信息</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/updating" title="如何把 Angular 应用和库升级到最新版本。" target="_self"><span>保持最新</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/releases" title="Angular 的版本、发布、支持、弃用策略及实践。" target="_self"><span>发布实践</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/updating-to-version-9" title="支持把你的应用从 8 升级到 9。" target="_self"><span>升级到第 9 版</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/deprecations" title="弃用的 Angular API 和特性汇总。" target="_self"><span>弃用清单</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/ivy" title="关于 Angular Ivy 的编译与渲染管道。" target="_self"><span>Angular Ivy</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-1 collapsed ng-star-inserted" title="Angular 语法、编码、术语汇总。" aria-pressed="false"><span>快捷手册</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/cheatsheet" title="关于 Angular 常用编码技术的快速指南。" target="_self"><span>速查表</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/styleguide" title="写出 Angular 风格的程序" target="_self"><span>风格指南</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/glossary" title="Angular 中最重要的词汇的简要定义。" target="_self"><span>词汇表</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button type="button" class="vertical-menu-item heading level-1 collapsed ng-star-inserted" title="Angular CLI 命令参考手册。" aria-pressed="false"><span>CLI 命令</span><mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli" title="CLI 工具介绍、命令、语法" target="_self"><span>概览</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/usage-analytics-gathering" title="管理员如何从用户那里收集使用情况分析。" target="_self"><span>使用情况分析</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/add" title="ng add." target="_self"><span>ng add</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/analytics" title="ng analytics." target="_self"><span>ng analytics</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/build" title="ng build." target="_self"><span>ng build</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/config" title="ng config." target="_self"><span>ng config</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/deploy" title="ng deploy." target="_self"><span>ng deploy</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/doc" title="ng doc." target="_self"><span>ng doc</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/e2e" title="ng e2e." target="_self"><span>ng e2e</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/generate" title="ng generate." target="_self"><span>ng generate</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/help" title="ng help." target="_self"><span>ng help</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/lint" title="ng lint." target="_self"><span>ng lint</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/new" title="ng new." target="_self"><span>ng new</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/run" title="ng run." target="_self"><span>ng run</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/serve" title="ng serve." target="_self"><span>ng serve</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/test" title="ng test." target="_self"><span>ng test</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/update" title="ng update." target="_self"><span>ng update</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/version" title="ng version." target="_self"><span>ng version</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/xi18n" title="ng xi18n." target="_self"><span>ng xi18n</span></a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="api" title="关于 Angular 中类和值的详细信息。" target="_self"><span>API 参考手册</span></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><div class="mat-divider ng-star-inserted" style="margin:4px 20px;border-top:1px solid #d3d3d3"></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="https://github.com/ng-docs/ng-docs.github.io/issues" title="github 上的中文互助问答区" target="_blank"><span>互助问答</span><mat-icon role="img" class="mat-icon notranslate material-icons mat-icon-no-color ng-star-inserted" aria-hidden="true">open_in_new</mat-icon></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="https://material.angular.cn" title="Angular Material 组件库的中文文档" target="_blank"><span>官方 Material 组件库</span><mat-icon role="img" class="mat-icon notranslate material-icons mat-icon-no-color ng-star-inserted" aria-hidden="true">open_in_new</mat-icon></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="https://ng.ant.design/" title="Ant Design 的 Angular 实现，服务于企业级后台产品。" target="_blank"><span>ng-zorro 组件库</span><mat-icon role="img" class="mat-icon notranslate material-icons mat-icon-no-color ng-star-inserted" aria-hidden="true">open_in_new</mat-icon></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="https://ng.mobile.ant.design/" title="Ant Design Mobile 的 Angular 实现，服务于无线产品。" target="_blank"><span>ng-zorro mobile 组件库</span><mat-icon role="img" class="mat-icon notranslate material-icons mat-icon-no-color ng-star-inserted" aria-hidden="true">open_in_new</mat-icon></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="https://flutter-io.cn/" title="Flutter 中文文档站" target="_blank"><span>友站：Flutter 中文</span><mat-icon role="img" class="mat-icon notranslate material-icons mat-icon-no-color ng-star-inserted" aria-hidden="true">open_in_new</mat-icon></a></div></aio-nav-item></aio-nav-menu><div class="doc-version ng-tns-c18-1"><aio-select><div class="form-select-menu"><button class="form-select-button"><span><strong></strong></span><span>stable (v9.0.0)</span></button></div></aio-select></div></div></mat-sidenav><div class="cdk-visually-hidden cdk-focus-trap-anchor" aria-hidden="true"></div><mat-sidenav-content cdkscrollable="" class="mat-drawer-content mat-sidenav-content ng-star-inserted" style="margin-left:261px"><main role="main" class="sidenav-content" id="guide-testing"><aio-mode-banner></aio-mode-banner><aio-doc-viewer class=""><div style="opacity:1"><div class="github-links"><a href="https://github.com/angular/angular-cn/edit/aio/aio/content/guide/testing.md?message=docs%3A%20请简述你的修改..." aria-label="提供编辑建议" title="提供编辑建议"><i class="material-icons" aria-hidden="true" role="img">mode_edit</i></a></div><div class="content"><a id="top"></a><h1 id="testing" translation-result="on">测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing"><i class="material-icons">link</i></a></h1><aio-toc class="embedded" ng-version="9.0.0-rc.11"><div class="toc-inner no-print collapsed ng-star-inserted"><button type="button" title="Expand/collapse contents" aria-label="Expand/collapse contents" class="toc-heading embedded secondary ng-star-inserted" aria-pressed="false">目录<mat-icon role="img" svgicon="keyboard_arrow_right" class="mat-icon notranslate rotating-icon collapsed mat-icon-no-color" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><ul class="toc-list embedded"><li class="h2 ng-star-inserted" title="建立环境"><a href="guide/testing#setup">建立环境</a></li><li class="h2 ng-star-inserted" title="建立持续集成环境"><a href="guide/testing#set-up-continuous-integration">建立持续集成环境</a></li><li class="h3 ng-star-inserted" title="为 Circle CI 配置项目"><a href="guide/testing#configure-project-for-circle-ci">为 Circle CI 配置项目</a></li><li class="h3 secondary ng-star-inserted" title="为 Travis CI 配置项目"><a href="guide/testing#configure-project-for-travis-ci">为 Travis CI 配置项目</a></li><li class="h3 secondary ng-star-inserted" title="为在 Chrome 中运行 CI 测试而配置 CLI"><a href="guide/testing#configure-cli-for-ci-testing-in-chrome">为在 Chrome 中运行 CI 测试而配置 CLI</a></li><li class="h2 secondary ng-star-inserted" title="启用代码覆盖率报告"><a href="guide/testing#enable-code-coverage-reports">启用代码覆盖率报告</a></li><li class="h3 secondary ng-star-inserted" title="代码覆盖率实施"><a href="guide/testing#code-coverage-enforcement">代码覆盖率实施</a></li><li class="h2 secondary ng-star-inserted" title="对服务的测试"><a href="guide/testing#service-tests">对服务的测试</a></li><li class="h2 secondary ng-star-inserted" title="组件测试基础"><a href="guide/testing#component-test-basics">组件测试基础</a></li><li class="h3 secondary ng-star-inserted" title="单独测试组件类"><a href="guide/testing#component-class-testing">单独测试组件类</a></li><li class="h3 secondary ng-star-inserted" title="组件 DOM 的测试"><a href="guide/testing#component-dom-testing">组件 DOM 的测试</a></li><li class="h2 secondary ng-star-inserted" title="组件测试场景"><a href="guide/testing#component-test-scenarios">组件测试场景</a></li><li class="h3 secondary ng-star-inserted" title="组件绑定"><a href="guide/testing#component-binding">组件绑定</a></li><li class="h3 secondary ng-star-inserted" title="带有外部文件的组件"><a href="guide/testing#component-with-external-files">带有外部文件的组件</a></li><li class="h3 secondary ng-star-inserted" title="带依赖的组件"><a href="guide/testing#component-with-a-dependency">带依赖的组件</a></li><li class="h3 secondary ng-star-inserted" title="带有异步服务的组件"><a href="guide/testing#component-with-async-service">带有异步服务的组件</a></li><li class="h3 secondary ng-star-inserted" title="组件的弹珠测试"><a href="guide/testing#component-marble-tests">组件的弹珠测试</a></li><li class="h3 secondary ng-star-inserted" title="带有输入输出参数的组件"><a href="guide/testing#component-with-inputs-and-outputs">带有输入输出参数的组件</a></li><li class="h3 secondary ng-star-inserted" title="位于测试宿主中的组件"><a href="guide/testing#component-inside-a-test-host">位于测试宿主中的组件</a></li><li class="h3 secondary ng-star-inserted" title="路由组件"><a href="guide/testing#routing-component">路由组件</a></li><li class="h3 secondary ng-star-inserted" title="路由目标组件"><a href="guide/testing#routed-components">路由目标组件</a></li><li class="h3 secondary ng-star-inserted" title="对嵌套组件的测试"><a href="guide/testing#nested-component-tests">对嵌套组件的测试</a></li><li class="h3 secondary ng-star-inserted" title="带有 RouterLink 的组件"><a href="guide/testing#components-with-routerlink">带有 <code>RouterLink</code> 的组件</a></li><li class="h3 secondary ng-star-inserted" title="使用页面（page）对象"><a href="guide/testing#use-a-page-object">使用页面（page）对象</a></li><li class="h3 secondary ng-star-inserted" title="调用 compileComponents()"><a href="guide/testing#calling-compilecomponents">调用 <code>compileComponents()</code></a></li><li class="h3 secondary ng-star-inserted" title="准备模块的 imports"><a href="guide/testing#setup-with-module-imports">准备模块的 <code>imports</code></a></li><li class="h3 secondary ng-star-inserted" title="改写组件的服务提供商"><a href="guide/testing#override-component-providers">改写组件的服务提供商</a></li><li class="h2 secondary ng-star-inserted" title="属性型指令的测试"><a href="guide/testing#attribute-directive-testing">属性型指令的测试</a></li><li class="h2 secondary ng-star-inserted" title="管道测试"><a href="guide/testing#pipe-testing">管道测试</a></li><li class="h2 secondary ng-star-inserted" title="测试程序的调试"><a href="guide/testing#test-debugging">测试程序的调试</a></li><li class="h2 secondary ng-star-inserted" title="测试工具 API"><a href="guide/testing#testing-utility-apis">测试工具 API</a></li><li class="h2 secondary ng-star-inserted" title="常见问题"><a href="guide/testing#frequently-asked-questions">常见问题</a></li></ul><button type="button" title="Expand/collapse contents" aria-label="Expand/collapse contents" class="toc-more-items embedded material-icons collapsed ng-star-inserted" aria-pressed="false"></button></div></aio-toc><h1 translation-origin="off" id="testing">Testing<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing"><i class="material-icons">link</i></a></h1><p translation-result="on">该指南提供了对 Angular 应用进行单元测试和集成测试的技巧和提示。</p><p translation-origin="off">This guide offers tips and techniques for unit and integration testing Angular applications.</p><p translation-result="on">该指南中的测试针对的是一个很像<a href="tutorial">《英雄指南》教程</a>的 <a href="cli">Angular CLI</a> 范例应用。 这个范例应用及其所有测试都可以在下面的链接中进行查看和试用：</p><p translation-origin="off">The guide presents tests of a sample application created with the <a href="cli">Angular CLI</a>. This sample application is much like the one created in the <a href="tutorial"><em>Tour of Heroes</em> tutorial</a>. The sample application and all tests in this guide are available for inspection and experimentation:</p><ul><li><p translation-result="on"><live-example embedded-style="" nodownload="" ng-version="9.0.0-rc.11"><span style="display:none">范例应用</span><span><span class="ng-star-inserted"><a target="_blank" title="范例应用" href="generated/live-examples/testing/stackblitz.html">范例应用</a></span></span></live-example></p><p translation-origin="off"><live-example embedded-style="" nodownload="" ng-version="9.0.0-rc.11"><span style="display:none">Sample app</span><span><span class="ng-star-inserted"><a target="_blank" title="Sample app" href="generated/live-examples/testing/stackblitz.html">Sample app</a></span></span></live-example></p></li><li><p translation-result="on"><live-example stackblitz="specs" nodownload="" ng-version="9.0.0-rc.11"><span style="display:none">测试</span><span><span class="ng-star-inserted"><a target="_blank" title="测试" href="generated/live-examples/testing/specs.stackblitz.html">测试</a></span></span></live-example></p><p translation-origin="off"><live-example stackblitz="specs" nodownload="" ng-version="9.0.0-rc.11"><span style="display:none">Tests</span><span><span class="ng-star-inserted"><a target="_blank" title="Tests" href="generated/live-examples/testing/specs.stackblitz.html">Tests</a></span></span></live-example></p></li></ul><hr><h2 id="setup" translation-result="on">建立环境<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#setup"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="setup">Setup<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#setup"><i class="material-icons">link</i></a></h2><p translation-result="on">Angular CLI 会下载并安装试用 <a href="https://jasmine.github.io/">Jasmine 测试框架</a> 测试 Angular 应用时所需的一切。</p><p translation-origin="off">The Angular CLI downloads and installs everything you need to test an Angular application with the <a href="https://jasmine.github.io/">Jasmine test framework</a>.</p><p translation-result="on">你使用 CLI 创建的项目是可以立即用于测试的。 运行 CLI 命令 <a href="cli/test"><code>ng test</code></a>即可：</p><p translation-origin="off">The project you create with the CLI is immediately ready to test. Just run the <a href="cli/test"><code>ng test</code></a>CLI command:</p><code-example language="sh" class="code-shell" ng-version="9.0.0-rc.11"><div style="display:none">ng test</div><aio-code><pre class="lang-sh prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">ng test</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>ng test</code> 命令在<em>监视模式</em>下构建应用，并启动 <a href="https://karma-runner.github.io">karma 测试运行器</a>。</p><p translation-origin="off">The <code>ng test</code> command builds the app in <em>watch mode</em>, and launches the <a href="https://karma-runner.github.io">Karma test runner</a>.</p><p translation-result="on">它的控制台输出一般是这样的：</p><p translation-origin="off">The console output looks a bit like this:</p><code-example language="sh" class="code-shell" ng-version="9.0.0-rc.11"><div style="display:none">10% building modules 1/1 modules 0 active ...INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/ ...INFO [launcher]: Launching browser Chrome ... ...INFO [launcher]: Starting browser Chrome ...INFO [Chrome ...]: Connected on socket ... Chrome ...: Executed 3 of 3 SUCCESS (0.135 secs / 0.205 secs)</div><aio-code><pre class="lang-sh prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">10</span><span class="pun">%</span><span class="pln"> building modules </span><span class="lit">1</span><span class="pun">/</span><span class="lit">1</span><span class="pln"> modules </span><span class="lit">0</span><span class="pln"> active
</span><span class="pun">...</span><span class="pln">INFO </span><span class="pun">[</span><span class="pln">karma</span><span class="pun">]:</span><span class="pln"> </span><span class="typ">Karma</span><span class="pln"> v1</span><span class="pun">.</span><span class="lit">7.1</span><span class="pln"> server started at http</span><span class="pun">://</span><span class="lit">0.0</span><span class="pun">.</span><span class="lit">0.0</span><span class="pun">:</span><span class="lit">9876</span><span class="pun">/</span><span class="pln">
</span><span class="pun">...</span><span class="pln">INFO </span><span class="pun">[</span><span class="pln">launcher</span><span class="pun">]:</span><span class="pln"> </span><span class="typ">Launching</span><span class="pln"> browser </span><span class="typ">Chrome</span><span class="pln"> </span><span class="pun">...</span><span class="pln">
</span><span class="pun">...</span><span class="pln">INFO </span><span class="pun">[</span><span class="pln">launcher</span><span class="pun">]:</span><span class="pln"> </span><span class="typ">Starting</span><span class="pln"> browser </span><span class="typ">Chrome</span><span class="pln">
</span><span class="pun">...</span><span class="pln">INFO </span><span class="pun">[</span><span class="typ">Chrome</span><span class="pln"> </span><span class="pun">...]:</span><span class="pln"> </span><span class="typ">Connected</span><span class="pln"> on socket </span><span class="pun">...</span><span class="pln">
</span><span class="typ">Chrome</span><span class="pln"> </span><span class="pun">...:</span><span class="pln"> </span><span class="typ">Executed</span><span class="pln"> </span><span class="lit">3</span><span class="pln"> of </span><span class="lit">3</span><span class="pln"> SUCCESS </span><span class="pun">(</span><span class="lit">0.135</span><span class="pln"> secs </span><span class="pun">/</span><span class="pln"> </span><span class="lit">0.205</span><span class="pln"> secs</span><span class="pun">)</span></code>
    </pre></aio-code></code-example><p translation-result="on">最后一行很重要。它表示 Karma 运行了三个测试，而且这些测试都通过了。</p><p translation-origin="off">The last line of the log is the most important. It shows that Karma ran three tests that all passed.</p><p translation-result="on">它还会打开 Chrome 浏览器并在“ Jasmine HTML 报告器”中显示测试输出，就像这样：</p><p translation-origin="off">A chrome browser also opens and displays the test output in the "Jasmine HTML Reporter" like this.</p><div class="lightbox"><img src="generated/images/guide/testing/initial-jasmine-html-reporter.png" alt="Jasmine HTML Reporter in the browser" width="502" height="306"></div><p translation-result="on">大多数人都会觉得浏览器中的报告比控制台中的日志更容易阅读。 你可以点击一行测试，来单独重跑这个测试，或者点击一行描述信息来重跑所选测试组（“测试套件”）中的那些测试。</p><p translation-origin="off">Most people find this browser output easier to read than the console log. You can click on a test row to re-run just that test or click on a description to re-run the tests in the selected test group ("test suite").</p><p translation-result="on">同时，<code>ng test</code> 命令还会监听这些变化。</p><p translation-origin="off">Meanwhile, the <code>ng test</code> command is watching for changes.</p><p translation-result="on">要查看它的实际效果，就对 <code>app.component.ts</code> 做一个小修改，并保存它。 这些测试就会重新运行，浏览器也会刷新，然后新的测试结果就出现了。</p><p translation-origin="off">To see this in action, make a small change to <code>app.component.ts</code> and save. The tests run again, the browser refreshes, and the new test results appear.</p><h4 id="configuration" translation-result="on">配置<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#configuration"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="configuration">Configuration<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#configuration"><i class="material-icons">link</i></a></h4><p translation-result="on">CLI 会为你生成 Jasmine 和 Karma 的配置文件。</p><p translation-origin="off">The CLI takes care of Jasmine and Karma configuration for you.</p><p translation-result="on">不过你也可以通过编辑 <code>src/</code> 目录下的 <code>karma.conf.js</code> 和 <code>test.ts</code> 文件来微调很多选项。</p><p translation-origin="off">You can fine-tune many options by editing the <code>karma.conf.js</code> and the <code>test.ts</code> files in the <code>src/</code> folder.</p><p translation-result="on"><code>karma.conf.js</code> 文件是 karma 配置文件的一部分。 CLI 会基于 <code>angular.json</code> 文件中指定的项目结构和 <code>karma.conf.js</code> 文件，来在内存中构建出完整的运行时配置。</p><p translation-origin="off">The <code>karma.conf.js</code> file is a partial Karma configuration file. The CLI constructs the full runtime configuration in memory, based on application structure specified in the <code>angular.json</code> file, supplemented by <code>karma.conf.js</code>.</p><p translation-result="on">要进一步了解 Jasmine 和 Karma 的配置项，请搜索网络。</p><p translation-origin="off">Search the web for more details about Jasmine and Karma configuration.</p><h4 id="other-test-frameworks" translation-result="on">其它测试框架<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#other-test-frameworks"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="other-test-frameworks">Other test frameworks<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#other-test-frameworks"><i class="material-icons">link</i></a></h4><p translation-result="on">你还可以使用其它的测试库和测试运行器来对 Angular 应用进行单元测试。 每个库和运行器都有自己特有的安装过程、配置项和语法。</p><p translation-origin="off">You can also unit test an Angular app with other testing libraries and test runners. Each library and runner has its own distinctive installation procedures, configuration, and syntax.</p><p translation-result="on">要了解更多，请搜索网络。</p><p translation-origin="off">Search the web to learn more.</p><h4 id="test-file-name-and-location" translation-result="on">测试文件名及其位置<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#test-file-name-and-location"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="test-file-name-and-location">Test file name and location<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#test-file-name-and-location"><i class="material-icons">link</i></a></h4><p translation-result="on">查看 <code>src/app</code> 文件夹。</p><p translation-origin="off">Look inside the <code>src/app</code> folder.</p><p translation-result="on">CLI 为 <code>AppComponent</code> 生成了一个名叫 <code>app.component.spec.ts</code> 的测试文件。</p><p translation-origin="off">The CLI generated a test file for the <code>AppComponent</code> named <code>app.component.spec.ts</code>.</p><div class="alert is-important"><p translation-result="on">测试文件的扩展名<strong>必须是 <code>.spec.ts</code></strong>，这样工具才能识别出它是一个测试文件，也叫规约（spec）文件。</p><p translation-origin="off">The test file extension <strong>must be <code>.spec.ts</code></strong>so that tooling can identify it as a file with tests (AKA, a <em>spec</em> file).</p></div><p translation-result="on"><code>app.component.ts</code> 和 <code>app.component.spec.ts</code> 文件位于同一个文件夹中，而且相邻。 其根文件名部分（<code>app.component</code>）都是一样的。</p><p translation-origin="off">The <code>app.component.ts</code> and <code>app.component.spec.ts</code> files are siblings in the same folder. The root file names (<code>app.component</code>) are the same for both files.</p><p translation-result="on">请在你的项目中对<em>任意类型</em>的测试文件都坚持这两条约定。</p><p translation-origin="off">Adopt these two conventions in your own projects for <em>every kind</em> of test file.</p><a id="ci"></a><h2 id="set-up-continuous-integration" translation-result="on">建立持续集成环境<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#set-up-continuous-integration"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="set-up-continuous-integration">Set up continuous integration<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#set-up-continuous-integration"><i class="material-icons">link</i></a></h2><p translation-result="on">避免项目出 BUG 的最佳方式之一，就是使用测试套件。但是很容易忘了一直运行它。 持续集成（CI）服务器让你可以配置项目的代码仓库，以便每次提交和收到 Pull Request 时就会运行你的测试。</p><p translation-origin="off">One of the best ways to keep your project bug free is through a test suite, but it's easy to forget to run tests all the time. Continuous integration (CI) servers let you set up your project repository so that your tests run on every commit and pull request.</p><p translation-result="on">已经有一些像 Circle CI 和 Travis CI 这样的付费 CI 服务器，你还可以使用 Jenkins 或其它软件来搭建你自己的免费 CI 服务器。 虽然 Circle CI 和 Travis CI 是收费服务，但是它们也会为开源项目提供免费服务。 你可以在 GitHub 上创建公开项目，并免费享受这些服务。 当你为 Angular 仓库贡献代码时，就会自动用 Circle CI 和 Travis CI 运行整个测试套件。</p><p translation-origin="off">There are paid CI services like Circle CI and Travis CI, and you can also host your own for free using Jenkins and others. Although Circle CI and Travis CI are paid services, they are provided free for open source projects. You can create a public project on GitHub and add these services without paying. Contributions to the Angular repo are automatically run through a whole suite of Circle CI tests.</p><p translation-result="on">本文档解释了如何配置你的项目，来运行 Circle CI 和 Travis CI，以及如何修改你的测试配置，以便能在这两个环境下用 Chrome 浏览器来运行测试。</p><p translation-origin="off">This article explains how to configure your project to run Circle CI and Travis CI, and also update your test configuration to be able to run tests in the Chrome browser in either environment.</p><h3 id="configure-project-for-circle-ci" translation-result="on">为 Circle CI 配置项目<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#configure-project-for-circle-ci"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="configure-project-for-circle-ci">Configure project for Circle CI<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#configure-project-for-circle-ci"><i class="material-icons">link</i></a></h3><p translation-result="on">步骤一：在项目的根目录下创建一个名叫 <code>.circleci</code> 的目录。</p><p translation-origin="off">Step 1: Create a folder called <code>.circleci</code> at the project root.</p><p translation-result="on">步骤二：在这个新建的目录下，创建一个名为 <code>config.yml</code> 的文件，内容如下：</p><p translation-origin="off">Step 2: In the new folder, create a file called <code>config.yml</code> with the following content:</p><code-example ng-version="9.0.0-rc.11"><div style="display:none">version: 2 jobs: build: working_directory: ~/my-project docker: - image: circleci/node:10-browsers steps: - checkout - restore_cache: key: my-project-{{ .Branch }}-{{ checksum "package-lock.json" }} - run: npm install - save_cache: key: my-project-{{ .Branch }}-{{ checksum "package-lock.json" }} paths: - "node_modules" - run: npm run test -- --no-watch --no-progress --browsers=ChromeHeadlessCI - run: npm run e2e -- --protractor-config=e2e/protractor-ci.conf.js</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">version</span><span class="pun">:</span><span class="pln"> </span><span class="lit">2</span><span class="pln">
jobs</span><span class="pun">:</span><span class="pln">
  build</span><span class="pun">:</span><span class="pln">
    working_directory</span><span class="pun">:</span><span class="pln"> </span><span class="pun">~/</span><span class="kwd">my</span><span class="pun">-</span><span class="pln">project
    docker</span><span class="pun">:</span><span class="pln">
      </span><span class="pun">-</span><span class="pln"> image</span><span class="pun">:</span><span class="pln"> circleci</span><span class="pun">/</span><span class="pln">node</span><span class="pun">:</span><span class="lit">10</span><span class="pun">-</span><span class="pln">browsers
    steps</span><span class="pun">:</span><span class="pln">
      </span><span class="pun">-</span><span class="pln"> checkout
      </span><span class="pun">-</span><span class="pln"> restore_cache</span><span class="pun">:</span><span class="pln">
          key</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">my</span><span class="pun">-</span><span class="pln">project</span><span class="pun">-{{</span><span class="pln"> </span><span class="pun">.</span><span class="typ">Branch</span><span class="pln"> </span><span class="pun">}}-{{</span><span class="pln"> checksum </span><span class="str">"package-lock.json"</span><span class="pln"> </span><span class="pun">}}</span><span class="pln">
      </span><span class="pun">-</span><span class="pln"> run</span><span class="pun">:</span><span class="pln"> npm install
      </span><span class="pun">-</span><span class="pln"> save_cache</span><span class="pun">:</span><span class="pln">
          key</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">my</span><span class="pun">-</span><span class="pln">project</span><span class="pun">-{{</span><span class="pln"> </span><span class="pun">.</span><span class="typ">Branch</span><span class="pln"> </span><span class="pun">}}-{{</span><span class="pln"> checksum </span><span class="str">"package-lock.json"</span><span class="pln"> </span><span class="pun">}}</span><span class="pln">
          paths</span><span class="pun">:</span><span class="pln">
            </span><span class="pun">-</span><span class="pln"> </span><span class="str">"node_modules"</span><span class="pln">
      </span><span class="pun">-</span><span class="pln"> run</span><span class="pun">:</span><span class="pln"> npm run test </span><span class="pun">--</span><span class="pln"> </span><span class="pun">--</span><span class="kwd">no</span><span class="pun">-</span><span class="pln">watch </span><span class="pun">--</span><span class="kwd">no</span><span class="pun">-</span><span class="pln">progress </span><span class="pun">--</span><span class="pln">browsers</span><span class="pun">=</span><span class="typ">ChromeHeadlessCI</span><span class="pln">
      </span><span class="pun">-</span><span class="pln"> run</span><span class="pun">:</span><span class="pln"> npm run e2e </span><span class="pun">--</span><span class="pln"> </span><span class="pun">--</span><span class="pln">protractor</span><span class="pun">-</span><span class="pln">config</span><span class="pun">=</span><span class="pln">e2e</span><span class="pun">/</span><span class="pln">protractor</span><span class="pun">-</span><span class="pln">ci</span><span class="pun">.</span><span class="pln">conf</span><span class="pun">.</span><span class="pln">js</span></code>
    </pre></aio-code></code-example><p translation-result="on">该配置会缓存 <code>node_modules/</code> 并使用 <a href="https://docs.npmjs.com/cli/run-script"><code>npm run</code></a>来运行 CLI 命令，因为 <code>@angular/cli</code> 并没有装到全局。 要把参数传给 <code>npm</code> 脚本，这个单独的双中线（<code>--</code>）是必须的。</p><p translation-origin="off">This configuration caches <code>node_modules/</code> and uses <a href="https://docs.npmjs.com/cli/run-script"><code>npm run</code></a>to run CLI commands, because <code>@angular/cli</code> is not installed globally. The double dash (<code>--</code>) is needed to pass arguments into the <code>npm</code> script.</p><p translation-result="on">步骤三：提交你的修改，并把它们推送到你的代码仓库中。</p><p translation-origin="off">Step 3: Commit your changes and push them to your repository.</p><p translation-result="on">步骤四：<a href="https://circleci.com/docs/2.0/first-steps/">注册 Circle CI</a>，并<a href="https://circleci.com/add-projects">添加你的项目</a>。你的项目将会开始构建。</p><p translation-origin="off">Step 4: <a href="https://circleci.com/docs/2.0/first-steps/">Sign up for Circle CI</a> and <a href="https://circleci.com/add-projects">add your project</a>. Your project should start building.</p><ul><li><p translation-result="on">欲知详情，参见 <a href="https://circleci.com/docs/2.0/">Circle CI 文档</a>。</p><p translation-origin="off">Learn more about Circle CI from <a href="https://circleci.com/docs/2.0/">Circle CI documentation</a>.</p></li></ul><h3 id="configure-project-for-travis-ci" translation-result="on">为 Travis CI 配置项目<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#configure-project-for-travis-ci"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="configure-project-for-travis-ci">Configure project for Travis CI<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#configure-project-for-travis-ci"><i class="material-icons">link</i></a></h3><p translation-result="on">步骤一：在项目根目录下创建一个名叫 <code>.travis.yml</code> 的文件，内容如下：</p><p translation-origin="off">Step 1: Create a file called <code>.travis.yml</code> at the project root, with the following content:</p><code-example ng-version="9.0.0-rc.11"><div style="display:none">dist: trusty sudo: false language: node_js node_js: - "10" addons: apt: sources: - google-chrome packages: - google-chrome-stable cache: directories: - ./node_modules install: - npm install script: - npm run test -- --no-watch --no-progress --browsers=ChromeHeadlessCI - npm run e2e -- --protractor-config=e2e/protractor-ci.conf.js</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">dist</span><span class="pun">:</span><span class="pln"> trusty
sudo</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">false</span><span class="pln">

language</span><span class="pun">:</span><span class="pln"> node_js
node_js</span><span class="pun">:</span><span class="pln">
  </span><span class="pun">-</span><span class="pln"> </span><span class="str">"10"</span><span class="pln">
addons</span><span class="pun">:</span><span class="pln">
  apt</span><span class="pun">:</span><span class="pln">
    sources</span><span class="pun">:</span><span class="pln">
      </span><span class="pun">-</span><span class="pln"> google</span><span class="pun">-</span><span class="pln">chrome
    packages</span><span class="pun">:</span><span class="pln">
      </span><span class="pun">-</span><span class="pln"> google</span><span class="pun">-</span><span class="pln">chrome</span><span class="pun">-</span><span class="pln">stable

cache</span><span class="pun">:</span><span class="pln">
  directories</span><span class="pun">:</span><span class="pln">
     </span><span class="pun">-</span><span class="pln"> </span><span class="pun">./</span><span class="pln">node_modules

install</span><span class="pun">:</span><span class="pln">
  </span><span class="pun">-</span><span class="pln"> npm install

script</span><span class="pun">:</span><span class="pln">
  </span><span class="pun">-</span><span class="pln"> npm run test </span><span class="pun">--</span><span class="pln"> </span><span class="pun">--</span><span class="kwd">no</span><span class="pun">-</span><span class="pln">watch </span><span class="pun">--</span><span class="kwd">no</span><span class="pun">-</span><span class="pln">progress </span><span class="pun">--</span><span class="pln">browsers</span><span class="pun">=</span><span class="typ">ChromeHeadlessCI</span><span class="pln">
  </span><span class="pun">-</span><span class="pln"> npm run e2e </span><span class="pun">--</span><span class="pln"> </span><span class="pun">--</span><span class="pln">protractor</span><span class="pun">-</span><span class="pln">config</span><span class="pun">=</span><span class="pln">e2e</span><span class="pun">/</span><span class="pln">protractor</span><span class="pun">-</span><span class="pln">ci</span><span class="pun">.</span><span class="pln">conf</span><span class="pun">.</span><span class="pln">js</span></code>
    </pre></aio-code></code-example><p translation-result="on">它做的事情和 Circle CI 的配置文件一样，只是 Travis 不用 Chrome，而是用 Chromium 代替。</p><p translation-origin="off">This does the same things as the Circle CI configuration, except that Travis doesn't come with Chrome, so we use Chromium instead.</p><p translation-result="on">步骤二：提交你的更改，并把它们推送到你的代码仓库。</p><p translation-origin="off">Step 2: Commit your changes and push them to your repository.</p><p translation-result="on">步骤三：<a href="https://travis-ci.org/auth">注册 Travis CI</a> 并<a href="https://travis-ci.org/profile">添加你的项目</a>。 你需要推送一个新的提交，以触发构建。</p><p translation-origin="off">Step 3: <a href="https://travis-ci.org/auth">Sign up for Travis CI</a> and <a href="https://travis-ci.org/profile">add your project</a>. You'll need to push a new commit to trigger a build.</p><ul><li><p translation-result="on">欲知详情，参见 <a href="https://docs.travis-ci.com/">Travis CI 文档</a>。</p><p translation-origin="off">Learn more about Travis CI testing from <a href="https://docs.travis-ci.com/">Travis CI documentation</a>.</p></li></ul><h3 id="configure-cli-for-ci-testing-in-chrome" translation-result="on">为在 Chrome 中运行 CI 测试而配置 CLI<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#configure-cli-for-ci-testing-in-chrome"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="configure-cli-for-ci-testing-in-chrome">Configure CLI for CI testing in Chrome<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#configure-cli-for-ci-testing-in-chrome"><i class="material-icons">link</i></a></h3><p translation-result="on">当 CLI 命令 <code>ng test</code> 和 <code>ng e2e</code> 经常要在你的环境中运行 CI 测试时，你可能需要再调整一下配置，以运行 Chrome 浏览器测试。</p><p translation-origin="off">When the CLI commands <code>ng test</code> and <code>ng e2e</code> are generally running the CI tests in your environment, you might still need to adjust your configuration to run the Chrome browser tests.</p><p translation-result="on">有一些文件是给 <a href="https://karma-runner.github.io/latest/config/configuration-file.html">Karma（直译 "报应"）</a>测试运行器和 <a href="https://www.protractortest.org/#/api-overview">Protractor（直译 "量角器"）</a> 端到端测试运行器使用的，你必须改为不用沙箱的 Chrome 启动方式。</p><p translation-origin="off">There are configuration files for both the <a href="https://karma-runner.github.io/latest/config/configuration-file.html">Karma JavaScript test runner</a> and <a href="https://www.protractortest.org/#/api-overview">Protractor</a> end-to-end testing tool, which you must adjust to start Chrome without sandboxing.</p><p translation-result="on">这个例子中我们将使用<a href="https://developers.google.com/web/updates/2017/04/headless-chrome#cli">无头 Chrome</a>。</p><p translation-origin="off">We'll be using <a href="https://developers.google.com/web/updates/2017/04/headless-chrome#cli">Headless Chrome</a> in these examples.</p><ul><li><p translation-result="on">在 Karma 配置文件 <code>karma.conf.js</code> 中，浏览器的紧下方，添加自定义的启动器，名叫 ChromeNoSandbox。</p><p translation-origin="off">In the Karma configuration file, <code>karma.conf.js</code>, add a custom launcher called ChromeHeadlessCI below browsers:</p></li></ul><code-example ng-version="9.0.0-rc.11"><div style="display:none">browsers: ['Chrome'], customLaunchers: { ChromeHeadlessCI: { base: 'ChromeHeadless', <a href="" class="code-anchor">flags</a>: ['--no-sandbox'] } },</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">browsers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="str">'Chrome'</span><span class="pun">],</span><span class="pln">
customLaunchers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="typ">ChromeHeadlessCI</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">base</span><span class="pun">:</span><span class="pln"> </span><span class="str">'ChromeHeadless'</span><span class="pun">,</span><span class="pln">
    </span><a href="" class="code-anchor"><span class="pln">flags</span></a><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="str">'--no-sandbox'</span><span class="pun">]</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">},</span></code>
    </pre></aio-code></code-example><ul><li><p translation-result="on">在 e2e 测试项目的根目录下创建一个新文件 <code>protractor-ci.conf.js</code>，它扩展了原始的 <code>protractor.conf.js</code>：</p><p translation-origin="off">In the root folder of your e2e tests project, create a new file named <code>protractor-ci.conf.js</code>. This new file extends the original <code>protractor.conf.js</code>.</p></li></ul><code-example ng-version="9.0.0-rc.11"><div style="display:none">const <a href="api/router/Router#config" class="code-anchor">config</a> = require('./protractor.conf').config; config.capabilities = { browserName: 'chrome', chromeOptions: { args: ['--headless', '--no-sandbox'] } }; exports.config = <a href="api/router/Router#config" class="code-anchor">config</a>;</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">const</span><span class="pln"> </span><a href="api/router/Router#config" class="code-anchor"><span class="pln">config</span></a><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">require</span><span class="pun">(</span><span class="str">'./protractor.conf'</span><span class="pun">).</span><span class="pln">config</span><span class="pun">;</span><span class="pln">

config</span><span class="pun">.</span><span class="pln">capabilities </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  browserName</span><span class="pun">:</span><span class="pln"> </span><span class="str">'chrome'</span><span class="pun">,</span><span class="pln">
  chromeOptions</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    args</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="str">'--headless'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'--no-sandbox'</span><span class="pun">]</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">};</span><span class="pln">

exports</span><span class="pun">.</span><span class="pln">config </span><span class="pun">=</span><span class="pln"> </span><a href="api/router/Router#config" class="code-anchor"><span class="pln">config</span></a><span class="pun">;</span></code>
    </pre></aio-code></code-example><p translation-result="on">现在你可以运行下列带有 <code>--no-sandbox</code> 标志的命令了：</p><p translation-origin="off">Now you can run the following commands to use the <code>--no-sandbox</code> flag:</p><code-example language="sh" class="code-shell" ng-version="9.0.0-rc.11"><div style="display:none">ng test --no-watch --no-progress --browsers=ChromeHeadlessCI ng e2e --protractor-config=e2e/protractor-ci.conf.js</div><aio-code><pre class="lang-sh prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">ng test </span><span class="pun">--</span><span class="pln">no</span><span class="pun">-</span><span class="pln">watch </span><span class="pun">--</span><span class="pln">no</span><span class="pun">-</span><span class="pln">progress </span><span class="pun">--</span><span class="pln">browsers</span><span class="pun">=</span><span class="typ">ChromeHeadlessCI</span><span class="pln">
ng e2e </span><span class="pun">--</span><span class="pln">protractor</span><span class="pun">-</span><span class="pln">config</span><span class="pun">=</span><span class="pln">e2e</span><span class="pun">/</span><span class="pln">protractor</span><span class="pun">-</span><span class="pln">ci</span><span class="pun">.</span><span class="pln">conf</span><span class="pun">.</span><span class="pln">js</span></code>
    </pre></aio-code></code-example><div class="alert is-helpful"><p translation-result="on"><strong>注意：</strong>目前，如果你正运行在 Windows 中，还要包含 <code>--disable-gpu</code> 标志。参见 <a href="https://crbug.com/737678">crbug.com/737678</a>。</p><p translation-origin="off"><strong>Note:</strong> Right now, you'll also want to include the <code>--disable-gpu</code> flag if you're running on Windows. See <a href="https://crbug.com/737678">crbug.com/737678</a>.</p></div><a id="code-coverage"></a><h2 id="enable-code-coverage-reports" translation-result="on">启用代码覆盖率报告<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#enable-code-coverage-reports"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="enable-code-coverage-reports">Enable code coverage reports<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#enable-code-coverage-reports"><i class="material-icons">link</i></a></h2><p translation-result="on">CLI 可以运行单元测试，并创建代码覆盖率报告。 代码覆盖率报告会向你展示代码库中有哪些可能未使用单元测试正常测试过的代码。</p><p translation-origin="off">The CLI can run unit tests and create code coverage reports. Code coverage reports show you any parts of our code base that may not be properly tested by your unit tests.</p><p translation-result="on">要生成覆盖率报告，请在项目的根目录下运行下列命令。</p><p translation-origin="off">To generate a coverage report run the following command in the root of your project.</p><code-example language="sh" class="code-shell" ng-version="9.0.0-rc.11"><div style="display:none">ng test --no-watch --code-coverage</div><aio-code><pre class="lang-sh prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">ng test </span><span class="pun">--</span><span class="pln">no</span><span class="pun">-</span><span class="pln">watch </span><span class="pun">--</span><span class="pln">code</span><span class="pun">-</span><span class="pln">coverage</span></code>
    </pre></aio-code></code-example><p translation-result="on">当测试完成时，该命令会在项目中创建一个新的 <code>/coverage</code> 目录。打开其 <code>index.html</code> 文件以查看带有源码和代码覆盖率值的报告。</p><p translation-origin="off">When the tests are complete, the command creates a new <code>/coverage</code> folder in the project. Open the <code>index.html</code> file to see a report with your source code and code coverage values.</p><p translation-result="on">如果你要在每次运行测试时都创建代码覆盖率报告，可以在 CLI 的配置文件 <code>angular.json</code> 中设置下列选项：</p><p translation-origin="off">If you want to create code-coverage reports every time you test, you can set the following option in the CLI configuration file, <code>angular.json</code>:</p><code-example ng-version="9.0.0-rc.11"><div style="display:none">"test": { "options": { "codeCoverage": true } }</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="str">"test"</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="str">"options"</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="str">"codeCoverage"</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">true</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><h3 id="code-coverage-enforcement" translation-result="on">代码覆盖率实施<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#code-coverage-enforcement"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="code-coverage-enforcement">Code coverage enforcement<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#code-coverage-enforcement"><i class="material-icons">link</i></a></h3><p translation-result="on">代码覆盖率能让你估计要测试的代码量。 如果你的开发组决定要设置单元测试的最小数量，就可以使用 Angular CLI 来守住这条底线。</p><p translation-origin="off">The code coverage percentages let you estimate how much of your code is tested. If your team decides on a set minimum amount to be unit tested, you can enforce this minimum with the Angular CLI.</p><p translation-result="on">比如，假设你希望代码有最少 80% 的代码覆盖率。 要启用它，请打开 <a href="https://karma-runner.github.io">Karma</a> 测试平台的配置文件 <code>karma.conf.js</code>，并添加键 <code>coverageIstanbulReporter:</code> 如下。</p><p translation-origin="off">For example, suppose you want the code base to have a minimum of 80% code coverage. To enable this, open the <a href="https://karma-runner.github.io">Karma</a> test platform configuration file, <code>karma.conf.js</code>, and add the following in the <code>coverageIstanbulReporter:</code> key.</p><code-example ng-version="9.0.0-rc.11"><div style="display:none">coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true, thresholds: { statements: 80, lines: 80, branches: 80, functions: 80 } }</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">coverageIstanbulReporter</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  reports</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="str">'html'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'lcovonly'</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
  fixWebpackSourcePaths</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">,</span><span class="pln">
  thresholds</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    statements</span><span class="pun">:</span><span class="pln"> </span><span class="lit">80</span><span class="pun">,</span><span class="pln">
    lines</span><span class="pun">:</span><span class="pln"> </span><span class="lit">80</span><span class="pun">,</span><span class="pln">
    branches</span><span class="pun">:</span><span class="pln"> </span><span class="lit">80</span><span class="pun">,</span><span class="pln">
    functions</span><span class="pun">:</span><span class="pln"> </span><span class="lit">80</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">这里的 <code>thresholds</code> 属性会让此工具在项目中运行单元测试时强制保证至少达到 80% 的测试覆盖率。</p><p translation-origin="off">The <code>thresholds</code> property causes the tool to enforce a minimum of 80% code coverage when the unit tests are run in the project.</p><h2 id="service-tests" translation-result="on">对服务的测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#service-tests"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="service-tests">Service Tests<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#service-tests"><i class="material-icons">link</i></a></h2><p translation-result="on">服务通常是单元测试中最简单的文件类型。 下面是一些针对 <code>ValueService</code> 的同步和异步单元测试， 编写它们时没有借助来自 Angular 测试工具集的任何协助。</p><p translation-origin="off">Services are often the easiest files to unit test. Here are some synchronous and asynchronous unit tests of the <code>ValueService</code> written without assistance from Angular testing utilities.</p><code-example path="testing/src/app/demo/demo.spec.ts" region="ValueService" header="app/demo/demo.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">// Straight Jasmine testing without Angular's testing support describe('ValueService', () =&gt; { let service: ValueService; beforeEach(() =&gt; { service = new ValueService(); }); it('#getValue should return real value', () =&gt; { expect(service.getValue()).toBe('real value'); }); it('#getObservableValue should return value from observable', (<a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>: DoneFn) =&gt; { service.getObservableValue().subscribe(value =&gt; { expect(value).toBe('observable value'); <a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>(); }); }); it('#getPromiseValue should return value from a promise', (<a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>: DoneFn) =&gt; { service.getPromiseValue().then(value =&gt; { expect(value).toBe('promise value'); <a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>(); }); }); });</div><header class="ng-star-inserted">app/demo/demo.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/demo/demo.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// Straight Jasmine testing without Angular's testing support</span><span class="pln">
describe</span><span class="pun">(</span><span class="str">'ValueService'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> service</span><span class="pun">:</span><span class="pln"> </span><span class="typ">ValueService</span><span class="pun">;</span><span class="pln">
  beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> service </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">ValueService</span><span class="pun">();</span><span class="pln"> </span><span class="pun">});</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'#getValue should return real value'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">service</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'real value'</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'#getObservableValue should return value from observable'</span><span class="pun">,</span><span class="pln">
    </span><span class="pun">(</span><a href="api/core/ApplicationInitStatus#done" class="code-anchor"><span class="kwd">done</span></a><span class="pun">:</span><span class="pln"> </span><span class="typ">DoneFn</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    service</span><span class="pun">.</span><span class="pln">getObservableValue</span><span class="pun">().</span><span class="pln">subscribe</span><span class="pun">(</span><span class="kwd">value</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
      expect</span><span class="pun">(</span><span class="kwd">value</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'observable value'</span><span class="pun">);</span><span class="pln">
      </span><a href="api/core/ApplicationInitStatus#done" class="code-anchor"><span class="kwd">done</span></a><span class="pun">();</span><span class="pln">
    </span><span class="pun">});</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'#getPromiseValue should return value from a promise'</span><span class="pun">,</span><span class="pln">
    </span><span class="pun">(</span><a href="api/core/ApplicationInitStatus#done" class="code-anchor"><span class="kwd">done</span></a><span class="pun">:</span><span class="pln"> </span><span class="typ">DoneFn</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    service</span><span class="pun">.</span><span class="pln">getPromiseValue</span><span class="pun">().</span><span class="kwd">then</span><span class="pun">(</span><span class="kwd">value</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
      expect</span><span class="pun">(</span><span class="kwd">value</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'promise value'</span><span class="pun">);</span><span class="pln">
      </span><a href="api/core/ApplicationInitStatus#done" class="code-anchor"><span class="kwd">done</span></a><span class="pun">();</span><span class="pln">
    </span><span class="pun">});</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><a id="services-with-dependencies"></a><h4 id="services-with-dependencies" translation-result="on">带有依赖的服务<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#services-with-dependencies"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="services-with-dependencies">Services with dependencies<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#services-with-dependencies"><i class="material-icons">link</i></a></h4><p translation-result="on">服务通常会依赖于一些 Angular 注入到其构造函数中的其它服务。 多数情况下，创建并在调用该服务的构造函数时，手工创建并注入这些依赖也是很容易的。</p><p translation-origin="off">Services often depend on other services that Angular injects into the constructor. In many cases, it's easy to create and <em>inject</em> these dependencies by hand while calling the service's constructor.</p><p translation-result="on"><code>MasterService</code> 就是一个简单的例子：</p><p translation-origin="off">The <code>MasterService</code> is a simple example:</p><code-example path="testing/src/app/demo/demo.ts" region="MasterService" header="app/demo/demo.ts" ng-version="9.0.0-rc.11"><div style="display:none">@<a href="api/core/Injectable" class="code-anchor">Injectable</a>() export class MasterService { constructor(private valueService: ValueService) { } getValue() { return this.valueService.getValue(); } }</div><header class="ng-star-inserted">app/demo/demo.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/demo/demo.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Injectable" class="code-anchor"><span class="lit">Injectable</span></a><span class="pun">()</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">MasterService</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="kwd">private</span><span class="pln"> valueService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">ValueService</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
  getValue</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">valueService</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>MasterService</code> 把它唯一的方法 <code>getValue</code> 委托给了注入进来的 <code>ValueService</code>。</p><p translation-origin="off"><code>MasterService</code> delegates its only method, <code>getValue</code>, to the injected <code>ValueService</code>.</p><p translation-result="on">这里是几种测试它的方法。</p><p translation-origin="off">Here are several ways to test it.</p><code-example path="testing/src/app/demo/demo.spec.ts" region="MasterService" header="app/demo/demo.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">describe('MasterService without Angular testing support', () =&gt; { let masterService: MasterService; it('#getValue should return real value from the real service', () =&gt; { masterService = new MasterService(new ValueService()); expect(masterService.getValue()).toBe('real value'); }); it('#getValue should return faked value from a fakeService', () =&gt; { masterService = new MasterService(new FakeValueService()); expect(masterService.getValue()).toBe('faked service value'); }); it('#getValue should return faked value from a fake object', () =&gt; { const fake = { getValue: () =&gt; 'fake value' }; masterService = new MasterService(fake as ValueService); expect(masterService.getValue()).toBe('fake value'); }); it('#getValue should return stubbed value from a spy', () =&gt; { // create `getValue` spy on an object representing the ValueService const valueServiceSpy = jasmine.createSpyObj('ValueService', ['getValue']); // set the value to return when the `getValue` spy is called. const stubValue = 'stub value'; valueServiceSpy.getValue.and.returnValue(stubValue); masterService = new MasterService(valueServiceSpy); expect(masterService.getValue()) .toBe(stubValue, 'service returned stub value'); expect(valueServiceSpy.getValue.calls.count()) .toBe(1, 'spy method was called once'); expect(valueServiceSpy.getValue.calls.mostRecent().returnValue) .toBe(stubValue); }); });</div><header class="ng-star-inserted">app/demo/demo.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/demo/demo.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">describe</span><span class="pun">(</span><span class="str">'MasterService without Angular testing support'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> masterService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">MasterService</span><span class="pun">;</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'#getValue should return real value from the real service'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    masterService </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">MasterService</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">ValueService</span><span class="pun">());</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">masterService</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'real value'</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'#getValue should return faked value from a fakeService'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    masterService </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">MasterService</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">FakeValueService</span><span class="pun">());</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">masterService</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'faked service value'</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'#getValue should return faked value from a fake object'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> fake </span><span class="pun">=</span><span class="pln">  </span><span class="pun">{</span><span class="pln"> getValue</span><span class="pun">:</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="str">'fake value'</span><span class="pln"> </span><span class="pun">};</span><span class="pln">
    masterService </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">MasterService</span><span class="pun">(</span><span class="pln">fake </span><span class="kwd">as</span><span class="pln"> </span><span class="typ">ValueService</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">masterService</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'fake value'</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'#getValue should return stubbed value from a spy'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="com">// create `getValue` spy on an object representing the ValueService</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> valueServiceSpy </span><span class="pun">=</span><span class="pln">
      jasmine</span><span class="pun">.</span><span class="pln">createSpyObj</span><span class="pun">(</span><span class="str">'ValueService'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">[</span><span class="str">'getValue'</span><span class="pun">]);</span><span class="pln">

    </span><span class="com">// set the value to return when the `getValue` spy is called.</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> stubValue </span><span class="pun">=</span><span class="pln"> </span><span class="str">'stub value'</span><span class="pun">;</span><span class="pln">
    valueServiceSpy</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">.</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">returnValue</span><span class="pun">(</span><span class="pln">stubValue</span><span class="pun">);</span><span class="pln">

    masterService </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">MasterService</span><span class="pun">(</span><span class="pln">valueServiceSpy</span><span class="pun">);</span><span class="pln">

    expect</span><span class="pun">(</span><span class="pln">masterService</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">())</span><span class="pln">
      </span><span class="pun">.</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">stubValue</span><span class="pun">,</span><span class="pln"> </span><span class="str">'service returned stub value'</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">valueServiceSpy</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">count</span><span class="pun">())</span><span class="pln">
      </span><span class="pun">.</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">1</span><span class="pun">,</span><span class="pln"> </span><span class="str">'spy method was called once'</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">valueServiceSpy</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">mostRecent</span><span class="pun">().</span><span class="pln">returnValue</span><span class="pun">)</span><span class="pln">
      </span><span class="pun">.</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">stubValue</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">第一个测试使用 <code>new</code> 创建了 <code>ValueService</code>，然后把它传给了 <code>MasterService</code> 的构造函数。</p><p translation-origin="off">The first test creates a <code>ValueService</code> with <code>new</code> and passes it to the <code>MasterService</code> constructor.</p><p translation-result="on">不过，对于大多数没这么容易创建和控制的依赖项来说，注入真实的服务很容易出问题。</p><p translation-origin="off">However, injecting the real service rarely works well as most dependent services are difficult to create and control.</p><p translation-result="on">你可以改用模拟依赖的方式，你可以使用虚值或在相关的服务方法上创建一个<a href="https://jasmine.github.io/2.0/introduction.html#section-Spies">间谍（spy）</a>。</p><p translation-origin="off">Instead you can mock the dependency, use a dummy value, or create a <a href="https://jasmine.github.io/2.0/introduction.html#section-Spies">spy</a> on the pertinent service method.</p><div class="alert is-helpful"><p translation-result="on">优先使用间谍，因为它们通常是 Mock 服务时最简单的方式。</p><p translation-origin="off">Prefer spies as they are usually the easiest way to mock services.</p></div><p translation-result="on">这些标准的测试技巧对于在隔离的环境下对服务进行单元测试非常重要。</p><p translation-origin="off">These standard testing techniques are great for unit testing services in isolation.</p><p translation-result="on">不过，你几乎迟早要用 Angular 的依赖注入机制来把服务注入到应用类中去，而且你应该已经有了这类测试。 Angular 的测试工具集可以让你轻松探查这种注入服务的工作方式。</p><p translation-origin="off">However, you almost always inject services into application classes using Angular dependency injection and you should have tests that reflect that usage pattern. Angular testing utilities make it easy to investigate how injected services behave.</p><h4 id="testing-services-with-the-testbed" translation-result="on">使用 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>（测试机床）测试服务<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-services-with-the-testbed"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="testing-services-with-the-testbed">Testing services with the <em>TestBed</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-services-with-the-testbed"><i class="material-icons">link</i></a></h4><p translation-result="on">你的应用中会依赖 Angular 的<a href="guide/dependency-injection">依赖注入 (DI)</a> 来创建服务。 当某个服务依赖另一个服务时，DI 就会找到或创建那个被依赖的服务。 如果那个被依赖的服务还有它自己的依赖，DI 也同样会找到或创建它们。</p><p translation-origin="off">Your app relies on Angular <a href="guide/dependency-injection">dependency injection (DI)</a> to create services. When a service has a dependent service, DI finds or creates that dependent service. And if that dependent service has its own dependencies, DI finds-or-creates them as well.</p><p translation-result="on">作为服务的<em>消费方</em>，你不需要关心这些细节。 你不用关心构造函数中的参数顺序或如何创建它们。</p><p translation-origin="off">As service <em>consumer</em>, you don't worry about any of this. You don't worry about the order of constructor arguments or how they're created.</p><p translation-result="on">但对于服务的<em>测试方</em>来说，你就至少要考虑服务的第一级依赖了。 不过你<em>可以</em>让 Angular DI 来负责服务的创建工作，但当你使用 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 测试工具来提供和创建服务时，你仍然需要关心构造函数中的参数顺序。</p><p translation-origin="off">As a service <em>tester</em>, you must at least think about the first level of service dependencies but you <em>can</em> let Angular DI do the service creation and deal with constructor argument order when you use the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> testing utility to provide and create services.</p><a id="testbed"></a><h4 id="angular-testbed">Angular <em>TestBed</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#angular-testbed"><i class="material-icons">link</i></a></h4><p translation-result="on"><code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 是 Angular 测试工具中最重要的部分。 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 会动态创建一个用来模拟 <a href="guide/ngmodules">@NgModule</a> 的 Angular <em>测试</em>模块。</p><p translation-origin="off">The <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> is the most important of the Angular testing utilities. The <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> creates a dynamically-constructed Angular <em>test</em> module that emulates an Angular <a href="guide/ngmodules">@NgModule</a>.</p><p translation-result="on"><code>TestBed.configureTestingModule()</code> 方法接收一个元数据对象，其中具有 <a href="guide/ngmodules">@NgModule</a> 中的绝大多数属性。</p><p translation-origin="off">The <code>TestBed.configureTestingModule()</code> method takes a metadata object that can have most of the properties of an <a href="guide/ngmodules">@NgModule</a>.</p><p translation-result="on">要测试某个服务，就要在元数据的 <code>providers</code> 属性中指定一个将要进行测试或模拟的相关服务的数组。</p><p translation-origin="off">To test a service, you set the <code>providers</code> metadata property with an array of the services that you'll test or mock.</p><code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="value-service-before-each" header="app/demo/demo.testbed.spec.ts (provide ValueService in beforeEach)" ng-version="9.0.0-rc.11"><div style="display:none">let service: ValueService; beforeEach(() =&gt; { TestBed.configureTestingModule({ providers: [ValueService] }); });</div><header class="ng-star-inserted">app/demo/demo.testbed.spec.ts (provide ValueService in beforeEach)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/demo/demo.testbed.spec.ts (provide ValueService in beforeEach)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">let</span><span class="pln"> service</span><span class="pun">:</span><span class="pln"> </span><span class="typ">ValueService</span><span class="pun">;</span><span class="pln">

beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln"> providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="typ">ValueService</span><span class="pun">]</span><span class="pln"> </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">然后通过调用 <code>TestBed.inject()</code>（参数为该服务类）把它注入到一个测试中。</p><p translation-origin="off">Then inject it inside a test by calling <code>TestBed.inject()</code> with the service class as the argument.</p><div class="alert is-helpful"><p translation-result="on"><strong>注意：</strong> 我们以前使用的是 <code>TestBed.get()</code>，而不是 <code>TestBed.inject()</code>。 <code>get</code> 方法不是类型安全的，它总是返回 <code>any</code>，这很容易出错。 考虑到大规模使用时会产生大量重大变更，我们决定将其迁移到新功能，而不是修改现有功能。</p><p translation-origin="off"><strong>Note:</strong> We used to have <code>TestBed.get()</code> instead of <code>TestBed.inject()</code>. The <code>get</code> method wasn't type safe, it always returned <code>any</code>, and this is error prone. We decided to migrate to a new function instead of updating the existing one given the large scale use that would have an immense amount of breaking changes.</p></div><code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="value-service-inject-it" ng-version="9.0.0-rc.11"><div style="display:none">it('should use ValueService', () =&gt; { service = TestBed.inject(ValueService); expect(service.getValue()).toBe('real value'); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should use ValueService'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  service </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">inject</span><span class="pun">(</span><span class="typ">ValueService</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">service</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'real value'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">或者，如果你更倾向于把该服务作为环境准备过程的一部分，就把它放在 <code>beforeEach()</code> 中。</p><p translation-origin="off">Or inside the <code>beforeEach()</code> if you prefer to inject the service as part of your setup.</p><code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="value-service-inject-before-each" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(() =&gt; { TestBed.configureTestingModule({ providers: [ValueService] }); service = TestBed.inject(ValueService); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln"> providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="typ">ValueService</span><span class="pun">]</span><span class="pln"> </span><span class="pun">});</span><span class="pln">
  service </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">inject</span><span class="pun">(</span><span class="typ">ValueService</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">如果要测试一个带有依赖项的服务，那就把模拟对象放在 <code>providers</code> 数组中。</p><p translation-origin="off">When testing a service with a dependency, provide the mock in the <code>providers</code> array.</p><p translation-result="on">在下面的例子中，模拟对象是一个间谍（spy）对象。</p><p translation-origin="off">In the following example, the mock is a spy object.</p><code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="master-service-before-each" ng-version="9.0.0-rc.11"><div style="display:none">let masterService: MasterService; let valueServiceSpy: jasmine.SpyObj&lt;ValueService&gt;; beforeEach(() =&gt; { const spy = jasmine.createSpyObj('ValueService', ['getValue']); TestBed.configureTestingModule({ // Provide both the service-to-test and its (spy) dependency providers: [ MasterService, { provide: ValueService, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: spy } ] }); // <a href="api/core/Inject" class="code-anchor">Inject</a> both the service-to-test and its (spy) dependency masterService = TestBed.inject(MasterService); valueServiceSpy = TestBed.inject(ValueService); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">let</span><span class="pln"> masterService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">MasterService</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">let</span><span class="pln"> valueServiceSpy</span><span class="pun">:</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="typ">SpyObj</span><span class="pun">&lt;</span><span class="typ">ValueService</span><span class="pun">&gt;;</span><span class="pln">

beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> spy </span><span class="pun">=</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="pln">createSpyObj</span><span class="pun">(</span><span class="str">'ValueService'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">[</span><span class="str">'getValue'</span><span class="pun">]);</span><span class="pln">

  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    </span><span class="com">// Provide both the service-to-test and its (spy) dependency</span><span class="pln">
    providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
      </span><span class="typ">MasterService</span><span class="pun">,</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><span class="typ">ValueService</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> spy </span><span class="pun">}</span><span class="pln">
    </span><span class="pun">]</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
  </span><span class="com">// </span><a href="api/core/Inject" class="code-anchor"><span class="com">Inject</span></a><span class="com"> both the service-to-test and its (spy) dependency</span><span class="pln">
  masterService </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">inject</span><span class="pun">(</span><span class="typ">MasterService</span><span class="pun">);</span><span class="pln">
  valueServiceSpy </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">inject</span><span class="pun">(</span><span class="typ">ValueService</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">该测试会像以前一样消费这个间谍对象。</p><p translation-origin="off">The test consumes that spy in the same way it did earlier.</p><code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="master-service-it" ng-version="9.0.0-rc.11"><div style="display:none">it('#getValue should return stubbed value from a spy', () =&gt; { const stubValue = 'stub value'; valueServiceSpy.getValue.and.returnValue(stubValue); expect(masterService.getValue()) .toBe(stubValue, 'service returned stub value'); expect(valueServiceSpy.getValue.calls.count()) .toBe(1, 'spy method was called once'); expect(valueServiceSpy.getValue.calls.mostRecent().returnValue) .toBe(stubValue); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'#getValue should return stubbed value from a spy'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> stubValue </span><span class="pun">=</span><span class="pln"> </span><span class="str">'stub value'</span><span class="pun">;</span><span class="pln">
  valueServiceSpy</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">.</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">returnValue</span><span class="pun">(</span><span class="pln">stubValue</span><span class="pun">);</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">masterService</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">())</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">stubValue</span><span class="pun">,</span><span class="pln"> </span><span class="str">'service returned stub value'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">valueServiceSpy</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">count</span><span class="pun">())</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">1</span><span class="pun">,</span><span class="pln"> </span><span class="str">'spy method was called once'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">valueServiceSpy</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">mostRecent</span><span class="pun">().</span><span class="pln">returnValue</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">stubValue</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><a id="no-before-each"></a><h4 id="testing-without-beforeeach" translation-result="on">不使用 <code>beforeEach</code> 进行测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-without-beforeeach"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="testing-without-beforeeach">Testing without <em>beforeEach()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-without-beforeeach"><i class="material-icons">link</i></a></h4><p translation-result="on">本指南中的大多数的测试套件都会调用 <code>beforeEach()</code> 来为每个 <code>it()</code> 测试准备前置条件，并依赖 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 来创建类和注入服务。</p><p translation-origin="off">Most test suites in this guide call <code>beforeEach()</code> to set the preconditions for each <code>it()</code> test and rely on the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> to create classes and inject services.</p><p translation-result="on">另一些测试教程中也可能让你不要调用 <code>beforeEach()</code>，并且更倾向于显式创建类，而不要借助 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>。</p><p translation-origin="off">There's another school of testing that never calls <code>beforeEach()</code> and prefers to create classes explicitly rather than use the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>.</p><p translation-result="on">下面的例子教你如何把 <code>MasterService</code> 的测试改写成那种风格。</p><p translation-origin="off">Here's how you might rewrite one of the <code>MasterService</code> tests in that style.</p><p translation-result="on">通过把可复用的准备代码放进一个单独的 <code>setup</code> 函数来代替 <code>beforeEach()</code>。</p><p translation-origin="off">Begin by putting re-usable, preparatory code in a <em>setup</em> function instead of <code>beforeEach()</code>.</p><code-example path="testing/src/app/demo/demo.spec.ts" region="no-before-each-setup" header="app/demo/demo.spec.ts (setup)" ng-version="9.0.0-rc.11"><div style="display:none">function setup() { const valueServiceSpy = jasmine.createSpyObj('ValueService', ['getValue']); const stubValue = 'stub value'; const masterService = new MasterService(valueServiceSpy); valueServiceSpy.getValue.and.returnValue(stubValue); return { masterService, stubValue, valueServiceSpy }; }</div><header class="ng-star-inserted">app/demo/demo.spec.ts (setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/demo/demo.spec.ts (setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">function</span><span class="pln"> setup</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> valueServiceSpy </span><span class="pun">=</span><span class="pln">
    jasmine</span><span class="pun">.</span><span class="pln">createSpyObj</span><span class="pun">(</span><span class="str">'ValueService'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">[</span><span class="str">'getValue'</span><span class="pun">]);</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> stubValue </span><span class="pun">=</span><span class="pln"> </span><span class="str">'stub value'</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> masterService </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">MasterService</span><span class="pun">(</span><span class="pln">valueServiceSpy</span><span class="pun">);</span><span class="pln">

  valueServiceSpy</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">.</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">returnValue</span><span class="pun">(</span><span class="pln">stubValue</span><span class="pun">);</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> masterService</span><span class="pun">,</span><span class="pln"> stubValue</span><span class="pun">,</span><span class="pln"> valueServiceSpy </span><span class="pun">};</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>setup()</code> 函数返回一个带有一些变量的对象字面量，比如 <code>masterService</code>，测试中可以引用它。 这样你就不用在 <code>describe()</code> 中定义一些<em>半全局性的</em>变量了（比如 <code>let masterService: MasterService</code> ）。</p><p translation-origin="off">The <code>setup()</code> function returns an object literal with the variables, such as <code>masterService</code>, that a test might reference. You don't define <em>semi-global</em> variables (e.g., <code>let masterService: MasterService</code>) in the body of the <code>describe()</code>.</p><p translation-result="on">然后，每个测试都会在第一行调用 <code>setup()</code>，然后再操纵被测主体以及对期望值进行断言。</p><p translation-origin="off">Then each test invokes <code>setup()</code> in its first line, before continuing with steps that manipulate the test subject and assert expectations.</p><code-example path="testing/src/app/demo/demo.spec.ts" region="no-before-each-test" ng-version="9.0.0-rc.11"><div style="display:none">it('#getValue should return stubbed value from a spy', () =&gt; { const { masterService, stubValue, valueServiceSpy } = setup(); expect(masterService.getValue()) .toBe(stubValue, 'service returned stub value'); expect(valueServiceSpy.getValue.calls.count()) .toBe(1, 'spy method was called once'); expect(valueServiceSpy.getValue.calls.mostRecent().returnValue) .toBe(stubValue); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'#getValue should return stubbed value from a spy'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> masterService</span><span class="pun">,</span><span class="pln"> stubValue</span><span class="pun">,</span><span class="pln"> valueServiceSpy </span><span class="pun">}</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> setup</span><span class="pun">();</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">masterService</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">())</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">stubValue</span><span class="pun">,</span><span class="pln"> </span><span class="str">'service returned stub value'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">valueServiceSpy</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">count</span><span class="pun">())</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">1</span><span class="pun">,</span><span class="pln"> </span><span class="str">'spy method was called once'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">valueServiceSpy</span><span class="pun">.</span><span class="pln">getValue</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">mostRecent</span><span class="pun">().</span><span class="pln">returnValue</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">stubValue</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">注意这些测试是如何使用 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">解构赋值</a> 来提取出所需变量的。</p><p translation-origin="off">Notice how the test uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment"><em>destructuring assignment</em></a> to extract the setup variables that it needs.</p><code-example path="testing/src/app/demo/demo.spec.ts" region="no-before-each-setup-call" ng-version="9.0.0-rc.11"><div style="display:none">const { masterService, stubValue, valueServiceSpy } = setup();</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">const</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> masterService</span><span class="pun">,</span><span class="pln"> stubValue</span><span class="pun">,</span><span class="pln"> valueServiceSpy </span><span class="pun">}</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> setup</span><span class="pun">();</span></code>
    </pre></aio-code></code-example><p translation-result="on">很多开发者觉得这种方式相比传统的 <code>beforeEach()</code> 风格更加干净、更加明确。</p><p translation-origin="off">Many developers feel this approach is cleaner and more explicit than the traditional <code>beforeEach()</code> style.</p><p translation-result="on">虽然本章会遵循传统的风格，并且 <a href="https://github.com/angular/devkit">CLI</a> 生成的默认测试文件也用的是 <code>beforeEach()</code> 和 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>，不过你可以在自己的项目中自由选择<em>这种可选方式</em>。</p><p translation-origin="off">Although this testing guide follows the traditional style and the default <a href="https://github.com/angular/angular-cli">CLI schematics</a> generate test files with <code>beforeEach()</code> and <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>, feel free to adopt <em>this alternative approach</em> in your own projects.</p><h4 id="testing-http-services" translation-result="on">测试 HTTP 服务<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-http-services"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="testing-http-services">Testing HTTP services<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-http-services"><i class="material-icons">link</i></a></h4><p translation-result="on">那些会向远端服务器发起 HTTP 调用的数据服务，通常会注入 Angular 的 <a href="guide/http"><code>HttpClient</code></a>服务并委托它进行 XHR 调用。</p><p translation-origin="off">Data services that make HTTP calls to remote servers typically inject and delegate to the Angular <a href="guide/http"><code>HttpClient</code></a>service for XHR calls.</p><p translation-result="on">你可以像测试其它带依赖的服务那样，通过注入一个 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 间谍来测试这种数据服务。</p><p translation-origin="off">You can test a data service with an injected <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> spy as you would test any service with a dependency.</p><code-example path="testing/src/app/model/hero.service.spec.ts" region="test-with-spies" header="app/model/hero.service.spec.ts (tests with spies)" ng-version="9.0.0-rc.11"><div style="display:none">let httpClientSpy: { get: jasmine.Spy }; let heroService: HeroService; beforeEach(() =&gt; { // TODO: spy on other methods too httpClientSpy = jasmine.createSpyObj('<a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a>', ['get']); heroService = new HeroService(&lt;any&gt; httpClientSpy); }); it('should return expected heroes (<a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a> called once)', () =&gt; { const expectedHeroes: Hero[] = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }]; httpClientSpy.get.and.returnValue(asyncData(expectedHeroes)); heroService.getHeroes().subscribe( heroes =&gt; expect(heroes).toEqual(expectedHeroes, 'expected heroes'), fail ); expect(httpClientSpy.get.calls.count()).toBe(1, 'one call'); }); it('should return an error when the server returns a 404', () =&gt; { const errorResponse = new <a href="api/common/http/HttpErrorResponse" class="code-anchor">HttpErrorResponse</a>({ error: 'test 404 error', status: 404, <a href="api/common/http/HttpResponseBase#statusText" class="code-anchor">statusText</a>: 'Not Found' }); httpClientSpy.get.and.returnValue(asyncError(errorResponse)); heroService.getHeroes().subscribe( heroes =&gt; fail('expected an error, not heroes'), error =&gt; expect(error.message).toContain('test 404 error') ); });</div><header class="ng-star-inserted">app/model/hero.service.spec.ts (tests with spies)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/model/hero.service.spec.ts (tests with spies)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">let</span><span class="pln"> httpClientSpy</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">get</span><span class="pun">:</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="typ">Spy</span><span class="pln"> </span><span class="pun">};</span><span class="pln">
</span><span class="kwd">let</span><span class="pln"> heroService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroService</span><span class="pun">;</span><span class="pln">

beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// TODO: spy on other methods too</span><span class="pln">
  httpClientSpy </span><span class="pun">=</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="pln">createSpyObj</span><span class="pun">(</span><span class="str">'</span><a href="api/common/http/HttpClient" class="code-anchor"><span class="str">HttpClient</span></a><span class="str">'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">[</span><span class="str">'get'</span><span class="pun">]);</span><span class="pln">
  heroService </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">HeroService</span><span class="pun">(&lt;</span><span class="pln">any</span><span class="pun">&gt;</span><span class="pln"> httpClientSpy</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should return expected heroes (</span><a href="api/common/http/HttpClient" class="code-anchor"><span class="str">HttpClient</span></a><span class="str"> called once)'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> expectedHeroes</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">[]</span><span class="pln"> </span><span class="pun">=</span><span class="pln">
    </span><span class="pun">[{</span><span class="pln"> id</span><span class="pun">:</span><span class="pln"> </span><span class="lit">1</span><span class="pun">,</span><span class="pln"> name</span><span class="pun">:</span><span class="pln"> </span><span class="str">'A'</span><span class="pln"> </span><span class="pun">},</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> id</span><span class="pun">:</span><span class="pln"> </span><span class="lit">2</span><span class="pun">,</span><span class="pln"> name</span><span class="pun">:</span><span class="pln"> </span><span class="str">'B'</span><span class="pln"> </span><span class="pun">}];</span><span class="pln">

  httpClientSpy</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">.</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">returnValue</span><span class="pun">(</span><span class="pln">asyncData</span><span class="pun">(</span><span class="pln">expectedHeroes</span><span class="pun">));</span><span class="pln">

  heroService</span><span class="pun">.</span><span class="pln">getHeroes</span><span class="pun">().</span><span class="pln">subscribe</span><span class="pun">(</span><span class="pln">
    heroes </span><span class="pun">=&gt;</span><span class="pln"> expect</span><span class="pun">(</span><span class="pln">heroes</span><span class="pun">).</span><span class="pln">toEqual</span><span class="pun">(</span><span class="pln">expectedHeroes</span><span class="pun">,</span><span class="pln"> </span><span class="str">'expected heroes'</span><span class="pun">),</span><span class="pln">
    fail
  </span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">httpClientSpy</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">count</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">1</span><span class="pun">,</span><span class="pln"> </span><span class="str">'one call'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should return an error when the server returns a 404'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> errorResponse </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><a href="api/common/http/HttpErrorResponse" class="code-anchor"><span class="typ">HttpErrorResponse</span></a><span class="pun">({</span><span class="pln">
    error</span><span class="pun">:</span><span class="pln"> </span><span class="str">'test 404 error'</span><span class="pun">,</span><span class="pln">
    status</span><span class="pun">:</span><span class="pln"> </span><span class="lit">404</span><span class="pun">,</span><span class="pln"> </span><a href="api/common/http/HttpResponseBase#statusText" class="code-anchor"><span class="pln">statusText</span></a><span class="pun">:</span><span class="pln"> </span><span class="str">'Not Found'</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  httpClientSpy</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">.</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">returnValue</span><span class="pun">(</span><span class="pln">asyncError</span><span class="pun">(</span><span class="pln">errorResponse</span><span class="pun">));</span><span class="pln">

  heroService</span><span class="pun">.</span><span class="pln">getHeroes</span><span class="pun">().</span><span class="pln">subscribe</span><span class="pun">(</span><span class="pln">
    heroes </span><span class="pun">=&gt;</span><span class="pln"> fail</span><span class="pun">(</span><span class="str">'expected an error, not heroes'</span><span class="pun">),</span><span class="pln">
    error  </span><span class="pun">=&gt;</span><span class="pln"> expect</span><span class="pun">(</span><span class="pln">error</span><span class="pun">.</span><span class="pln">message</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="str">'test 404 error'</span><span class="pun">)</span><span class="pln">
  </span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><div class="alert is-important"><p translation-result="on"><code>HttpService</code> 中的方法会返回 <code>Observables</code>。<em>订阅</em>这些方法返回的可观察对象会让它开始执行，并且断言这些方法是成功了还是失败了。</p><p translation-origin="off">The <code>HeroService</code> methods return <code>Observables</code>. You must <em>subscribe</em> to an observable to (a) cause it to execute and (b) assert that the method succeeds or fails.</p><p translation-result="on"><code>subscribe()</code> 方法接受一个成功回调 (<code>next</code>) 和一个失败 (<code>error</code>) 回调。 你要确保同时提供了这两个回调，以便捕获错误。 如果忽略这些异步调用中未捕获的错误，测试运行器可能会得出截然不同的测试结论。</p><p translation-origin="off">The <code>subscribe()</code> method takes a success (<code>next</code>) and fail (<code>error</code>) callback. Make sure you provide <em>both</em> callbacks so that you capture errors. Neglecting to do so produces an asynchronous uncaught observable error that the test runner will likely attribute to a completely different test.</p></div><h4 id="httpclienttestingmodule"><em>HttpClientTestingModule</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#httpclienttestingmodule"><i class="material-icons">link</i></a></h4><p translation-result="on">如果将来 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 和数据服务之间有更多的交互，则可能会变得复杂，而且难以使用间谍进行模拟。</p><p translation-origin="off">Extended interactions between a data service and the <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> can be complex and difficult to mock with spies.</p><p translation-result="on"><code><a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor">HttpClientTestingModule</a></code> 可以让这些测试场景变得更加可控。</p><p translation-origin="off">The <code><a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor">HttpClientTestingModule</a></code> can make these testing scenarios more manageable.</p><p translation-result="on">本章的<em>代码范例</em>要示范的是 <code><a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor">HttpClientTestingModule</a></code>，所以把部分内容移到了 <a href="guide/http#testing-http-requests">Http</a> 一章，那里会详细讲解如何用 <code><a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor">HttpClientTestingModule</a></code> 进行测试。</p><p translation-origin="off">While the <em>code sample</em> accompanying this guide demonstrates <code><a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor">HttpClientTestingModule</a></code>, this page defers to the <a href="guide/http#testing-http-requests">Http guide</a>, which covers testing with the <code><a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor">HttpClientTestingModule</a></code> in detail.</p><h2 id="component-test-basics" translation-result="on">组件测试基础<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-test-basics"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="component-test-basics">Component Test Basics<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-test-basics"><i class="material-icons">link</i></a></h2><p translation-result="on">组件与 Angular 应用中的其它部分不同，它是由 HTML 模板和 TypeScript 类组成的。 组件其实是指模板加上与其合作的类。 要想对组件进行充分的测试，就要测试它们能否如预期的那样协作。</p><p translation-origin="off">A component, unlike all other parts of an Angular application, combines an HTML template and a TypeScript class. The component truly is the template and the class <em>working together</em>. To adequately test a component, you should test that they work together as intended.</p><p translation-result="on">这些测试需要在浏览器的 DOM 中创建组件的宿主元素（就像 Angular 所做的那样），然后检查组件类和 DOM 的交互是否如同它在模板中所描述的那样。</p><p translation-origin="off">Such tests require creating the component's host element in the browser DOM, as Angular does, and investigating the component class's interaction with the DOM as described by its template.</p><p translation-result="on">Angular 的 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 为所有这些类型的测试提供了基础设施。 但是很多情况下，可以<em>单独测试组件类本身</em>而不必涉及 DOM，就已经可以用一种更加简单、清晰的方式来验证该组件的大多数行为了。</p><p translation-origin="off">The Angular <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> facilitates this kind of testing as you'll see in the sections below. But in many cases, <em>testing the component class alone</em>, without DOM involvement, can validate much of the component's behavior in an easier, more obvious way.</p><h3 id="component-class-testing" translation-result="on">单独测试组件类<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-class-testing"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="component-class-testing">Component class testing<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-class-testing"><i class="material-icons">link</i></a></h3><p translation-result="on">你可以像测试服务类一样测试组件类。</p><p translation-origin="off">Test a component class on its own as you would test a service class.</p><p translation-result="on">考虑下面这个 <code>LightswitchComponent</code>，当用户点击按钮时，它会切换灯的开关状态（用屏幕上的消息展现出来）。</p><p translation-origin="off">Consider this <code>LightswitchComponent</code> which toggles a light on and off (represented by an on-screen message) when the user clicks the button.</p><code-example path="testing/src/app/demo/demo.ts" region="LightswitchComp" header="app/demo/demo.ts (LightswitchComp)" ng-version="9.0.0-rc.11"><div style="display:none">@<a href="api/core/Component" class="code-anchor">Component</a>({ selector: 'lightswitch-comp', template: ` &lt;button (click)="clicked()"&gt;Click me!&lt;/button&gt; &lt;span&gt;{{<a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a>}}&lt;/span&gt;` }) export class LightswitchComponent { isOn = false; clicked() { this.isOn = !this.isOn; } get <a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a>() { return `The light is ${this.isOn ? 'On' : 'Off'}`; } }</div><header class="ng-star-inserted">app/demo/demo.ts (LightswitchComp)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/demo/demo.ts (LightswitchComp)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">
  selector</span><span class="pun">:</span><span class="pln"> </span><span class="str">'lightswitch-comp'</span><span class="pun">,</span><span class="pln">
  </span><span class="kwd">template</span><span class="pun">:</span><span class="pln"> </span><span class="str">`
    &lt;button (click)="clicked()"&gt;Click me!&lt;/button&gt;
    &lt;span&gt;{{</span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="str">message</span></a><span class="str">}}&lt;/span&gt;`</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">LightswitchComponent</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  isOn </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">false</span><span class="pun">;</span><span class="pln">
  clicked</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">isOn </span><span class="pun">=</span><span class="pln"> </span><span class="pun">!</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">isOn</span><span class="pun">;</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
  </span><span class="kwd">get</span><span class="pln"> </span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="pln">message</span></a><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="str">`The light is ${this.isOn ? 'On' : 'Off'}`</span><span class="pun">;</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">你可能要测试 <code>clicked()</code> 方法能否正确切换灯的开关状态并设置合适的消息。</p><p translation-origin="off">You might decide only to test that the <code>clicked()</code> method toggles the light's <em>on/off</em> state and sets the message appropriately.</p><p translation-result="on">该组件类没有依赖。 要测试一个没有依赖的服务，你会用 <code>new</code> 来创建它，调用它的 API，然后对它的公开状态进行断言。 组件类也可以这么做。</p><p translation-origin="off">This component class has no dependencies. To test a service with no dependencies, you create it with <code>new</code>, poke at its API, and assert expectations on its public state. Do the same with the component class.</p><code-example path="testing/src/app/demo/demo.spec.ts" region="Lightswitch" header="app/demo/demo.spec.ts (Lightswitch tests)" ng-version="9.0.0-rc.11"><div style="display:none">describe('LightswitchComp', () =&gt; { it('#clicked() should toggle #isOn', () =&gt; { const comp = new LightswitchComponent(); expect(comp.isOn).toBe(false, 'off at first'); comp.clicked(); expect(comp.isOn).toBe(true, 'on after click'); comp.clicked(); expect(comp.isOn).toBe(false, 'off after second click'); }); it('#clicked() should set #<a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a> to "is on"', () =&gt; { const comp = new LightswitchComponent(); expect(comp.message).toMatch(/is off/i, 'off at first'); comp.clicked(); expect(comp.message).toMatch(/is on/i, 'on after clicked'); }); });</div><header class="ng-star-inserted">app/demo/demo.spec.ts (Lightswitch tests)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/demo/demo.spec.ts (Lightswitch tests)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">describe</span><span class="pun">(</span><span class="str">'LightswitchComp'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  it</span><span class="pun">(</span><span class="str">'#clicked() should toggle #isOn'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> comp </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">LightswitchComponent</span><span class="pun">();</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">comp</span><span class="pun">.</span><span class="pln">isOn</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">false</span><span class="pun">,</span><span class="pln"> </span><span class="str">'off at first'</span><span class="pun">);</span><span class="pln">
    comp</span><span class="pun">.</span><span class="pln">clicked</span><span class="pun">();</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">comp</span><span class="pun">.</span><span class="pln">isOn</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">,</span><span class="pln"> </span><span class="str">'on after click'</span><span class="pun">);</span><span class="pln">
    comp</span><span class="pun">.</span><span class="pln">clicked</span><span class="pun">();</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">comp</span><span class="pun">.</span><span class="pln">isOn</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">false</span><span class="pun">,</span><span class="pln"> </span><span class="str">'off after second click'</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'#clicked() should set #</span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="str">message</span></a><span class="str"> to "is on"'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> comp </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">LightswitchComponent</span><span class="pun">();</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">comp</span><span class="pun">.</span><span class="pln">message</span><span class="pun">).</span><span class="pln">toMatch</span><span class="pun">(</span><span class="str">/is off/</span><span class="pln">i</span><span class="pun">,</span><span class="pln"> </span><span class="str">'off at first'</span><span class="pun">);</span><span class="pln">
    comp</span><span class="pun">.</span><span class="pln">clicked</span><span class="pun">();</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">comp</span><span class="pun">.</span><span class="pln">message</span><span class="pun">).</span><span class="pln">toMatch</span><span class="pun">(</span><span class="str">/is on/</span><span class="pln">i</span><span class="pun">,</span><span class="pln"> </span><span class="str">'on after clicked'</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">下面这段代码是来自《英雄指南》教程的 <code>DashboardHeroComponent</code>。</p><p translation-origin="off">Here is the <code>DashboardHeroComponent</code> from the <em>Tour of Heroes</em> tutorial.</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.ts" region="class" header="app/dashboard/dashboard-hero.component.ts (component)" ng-version="9.0.0-rc.11"><div style="display:none">export class DashboardHeroComponent { @<a href="api/core/Input" class="code-anchor">Input</a>() hero: Hero; @<a href="api/core/Output" class="code-anchor">Output</a>() selected = new <a href="api/core/EventEmitter" class="code-anchor">EventEmitter</a>&lt;Hero&gt;(); click() { this.selected.emit(this.hero); } }</div><header class="ng-star-inserted">app/dashboard/dashboard-hero.component.ts (component)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard-hero.component.ts (component)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">DashboardHeroComponent</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="lit">@</span><a href="api/core/Input" class="code-anchor"><span class="lit">Input</span></a><span class="pun">()</span><span class="pln"> hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">;</span><span class="pln">
  </span><span class="lit">@</span><a href="api/core/Output" class="code-anchor"><span class="lit">Output</span></a><span class="pun">()</span><span class="pln"> selected </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><a href="api/core/EventEmitter" class="code-anchor"><span class="typ">EventEmitter</span></a><span class="pun">&lt;</span><span class="typ">Hero</span><span class="pun">&gt;();</span><span class="pln">
  click</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">selected</span><span class="pun">.</span><span class="pln">emit</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">hero</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">它呈现在父组件的模板中，那里把一个英雄绑定到了 <code>@<a href="api/core/Input" class="code-anchor">Input</a></code> 属性上，并且通过 <code>@<a href="api/core/Output" class="code-anchor">Output</a></code> 属性监听<em>选中英雄</em>时的事件。</p><p translation-origin="off">It appears within the template of a parent component, which binds a <em>hero</em> to the <code>@<a href="api/core/Input" class="code-anchor">Input</a></code> property and listens for an event raised through the <em>selected</em> <code>@<a href="api/core/Output" class="code-anchor">Output</a></code> property.</p><p translation-result="on">你可以测试 <code>DashboardHeroComponent</code> 类，而不用完整创建它或其父组件。</p><p translation-origin="off">You can test that the class code works without creating the <code>DashboardHeroComponent</code> or its parent component.</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.spec.ts" region="class-only" header="app/dashboard/dashboard-hero.component.spec.ts (class tests)" ng-version="9.0.0-rc.11"><div style="display:none">it('raises the selected event when clicked', () =&gt; { const comp = new DashboardHeroComponent(); const hero: Hero = { id: 42, name: 'Test' }; comp.hero = hero; comp.selected.subscribe((selectedHero: Hero) =&gt; expect(selectedHero).toBe(hero)); comp.click(); });</div><header class="ng-star-inserted">app/dashboard/dashboard-hero.component.spec.ts (class tests)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard-hero.component.spec.ts (class tests)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'raises the selected event when clicked'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> comp </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">DashboardHeroComponent</span><span class="pun">();</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> id</span><span class="pun">:</span><span class="pln"> </span><span class="lit">42</span><span class="pun">,</span><span class="pln"> name</span><span class="pun">:</span><span class="pln"> </span><span class="str">'Test'</span><span class="pln"> </span><span class="pun">};</span><span class="pln">
  comp</span><span class="pun">.</span><span class="pln">hero </span><span class="pun">=</span><span class="pln"> hero</span><span class="pun">;</span><span class="pln">

  comp</span><span class="pun">.</span><span class="pln">selected</span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">((</span><span class="pln">selectedHero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> expect</span><span class="pun">(</span><span class="pln">selectedHero</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">hero</span><span class="pun">));</span><span class="pln">
  comp</span><span class="pun">.</span><span class="pln">click</span><span class="pun">();</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">当组件有依赖时，你可能要使用 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 来同时创建该组件及其依赖。</p><p translation-origin="off">When a component has dependencies, you may wish to use the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> to both create the component and its dependencies.</p><p translation-result="on">下面的 <code>WelcomeComponent</code> 依赖于 <code>UserService</code>，并通过它知道要打招呼的那位用户的名字。</p><p translation-origin="off">The following <code>WelcomeComponent</code> depends on the <code>UserService</code> to know the name of the user to greet.</p><code-example path="testing/src/app/welcome/welcome.component.ts" region="class" header="app/welcome/welcome.component.ts" ng-version="9.0.0-rc.11"><div style="display:none">export class WelcomeComponent implements <a href="api/core/OnInit" class="code-anchor">OnInit</a> { welcome: string; constructor(private userService: UserService) { } ngOnInit(): void { this.welcome = this.userService.isLoggedIn ? 'Welcome, ' + this.userService.user.name : 'Please <a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor">log</a> in.'; } }</div><header class="ng-star-inserted">app/welcome/welcome.component.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/welcome/welcome.component.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WelcomeComponent</span><span class="pln">  </span><span class="kwd">implements</span><span class="pln"> </span><a href="api/core/OnInit" class="code-anchor"><span class="typ">OnInit</span></a><span class="pln"> </span><span class="pun">{</span><span class="pln">
  welcome</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="kwd">private</span><span class="pln"> userService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">UserService</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">}</span><span class="pln">

  ngOnInit</span><span class="pun">():</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">welcome </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">userService</span><span class="pun">.</span><span class="pln">isLoggedIn </span><span class="pun">?</span><span class="pln">
      </span><span class="str">'Welcome, '</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">userService</span><span class="pun">.</span><span class="pln">user</span><span class="pun">.</span><span class="pln">name </span><span class="pun">:</span><span class="pln"> </span><span class="str">'Please </span><a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor"><span class="str">log</span></a><span class="str"> in.'</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">你可能要先创建一个满足本组件最小需求的模拟版 <code>UserService</code>。</p><p translation-origin="off">You might start by creating a mock of the <code>UserService</code> that meets the minimum needs of this component.</p><code-example path="testing/src/app/welcome/welcome.component.spec.ts" region="mock-user-service" header="app/welcome/welcome.component.spec.ts (MockUserService)" ng-version="9.0.0-rc.11"><div style="display:none">class MockUserService { isLoggedIn = true; user = { name: 'Test <a href="api/common/http/HttpEventType#User" class="code-anchor">User</a>'}; };</div><header class="ng-star-inserted">app/welcome/welcome.component.spec.ts (MockUserService)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/welcome/welcome.component.spec.ts (MockUserService)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">class</span><span class="pln"> </span><span class="typ">MockUserService</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  isLoggedIn </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">;</span><span class="pln">
  user </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> name</span><span class="pun">:</span><span class="pln"> </span><span class="str">'Test </span><a href="api/common/http/HttpEventType#User" class="code-anchor"><span class="str">User</span></a><span class="str">'</span><span class="pun">};</span><span class="pln">
</span><span class="pun">};</span></code>
    </pre></aio-code></code-example><p translation-result="on">然后在 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 的配置中提供并同时注入该<strong>组件</strong>和该<strong>服务</strong>。</p><p translation-origin="off">Then provide and inject <em>both the</em> <strong>component</strong> <em>and the service</em> in the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> configuration.</p><code-example path="testing/src/app/welcome/welcome.component.spec.ts" region="class-only-before-each" header="app/welcome/welcome.component.spec.ts (class-only setup)" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(() =&gt; { TestBed.configureTestingModule({ // provide the component-under-test and dependent service providers: [ WelcomeComponent, { provide: UserService, useClass: MockUserService } ] }); // inject both the component and the dependent service. comp = TestBed.inject(WelcomeComponent); userService = TestBed.inject(UserService); });</div><header class="ng-star-inserted">app/welcome/welcome.component.spec.ts (class-only setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/welcome/welcome.component.spec.ts (class-only setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    </span><span class="com">// provide the component-under-test and dependent service</span><span class="pln">
    providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
      </span><span class="typ">WelcomeComponent</span><span class="pun">,</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><span class="typ">UserService</span><span class="pun">,</span><span class="pln"> useClass</span><span class="pun">:</span><span class="pln"> </span><span class="typ">MockUserService</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
    </span><span class="pun">]</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
  </span><span class="com">// inject both the component and the dependent service.</span><span class="pln">
  comp </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">inject</span><span class="pun">(</span><span class="typ">WelcomeComponent</span><span class="pun">);</span><span class="pln">
  userService </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">inject</span><span class="pun">(</span><span class="typ">UserService</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">然后使用这个组件类，别忘了像 Angular 运行本应用时那样调用它的<a href="guide/lifecycle-hooks">生命周期钩子方法</a>。</p><p translation-origin="off">Then exercise the component class, remembering to call the <a href="guide/lifecycle-hooks">lifecycle hook methods</a> as Angular does when running the app.</p><code-example path="testing/src/app/welcome/welcome.component.spec.ts" region="class-only-tests" header="app/welcome/welcome.component.spec.ts (class-only tests)" ng-version="9.0.0-rc.11"><div style="display:none">it('should not have welcome <a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a> after construction', () =&gt; { expect(comp.welcome).toBeUndefined(); }); it('should welcome logged in user after Angular calls ngOnInit', () =&gt; { comp.ngOnInit(); expect(comp.welcome).toContain(userService.user.name); }); it('should ask user to <a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor">log</a> in if not logged in after ngOnInit', () =&gt; { userService.isLoggedIn = false; comp.ngOnInit(); expect(comp.welcome).not.toContain(userService.user.name); expect(comp.welcome).toContain('<a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor">log</a> in'); });</div><header class="ng-star-inserted">app/welcome/welcome.component.spec.ts (class-only tests)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/welcome/welcome.component.spec.ts (class-only tests)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should not have welcome </span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="str">message</span></a><span class="str"> after construction'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">comp</span><span class="pun">.</span><span class="pln">welcome</span><span class="pun">).</span><span class="pln">toBeUndefined</span><span class="pun">();</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should welcome logged in user after Angular calls ngOnInit'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  comp</span><span class="pun">.</span><span class="pln">ngOnInit</span><span class="pun">();</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">comp</span><span class="pun">.</span><span class="pln">welcome</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="pln">userService</span><span class="pun">.</span><span class="pln">user</span><span class="pun">.</span><span class="pln">name</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should ask user to </span><a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor"><span class="str">log</span></a><span class="str"> in if not logged in after ngOnInit'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  userService</span><span class="pun">.</span><span class="pln">isLoggedIn </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">false</span><span class="pun">;</span><span class="pln">
  comp</span><span class="pun">.</span><span class="pln">ngOnInit</span><span class="pun">();</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">comp</span><span class="pun">.</span><span class="pln">welcome</span><span class="pun">).</span><span class="kwd">not</span><span class="pun">.</span><span class="pln">toContain</span><span class="pun">(</span><span class="pln">userService</span><span class="pun">.</span><span class="pln">user</span><span class="pun">.</span><span class="pln">name</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">comp</span><span class="pun">.</span><span class="pln">welcome</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="str">'</span><a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor"><span class="str">log</span></a><span class="str"> in'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><h3 id="component-dom-testing" translation-result="on">组件 DOM 的测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-dom-testing"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="component-dom-testing">Component DOM testing<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-dom-testing"><i class="material-icons">link</i></a></h3><p translation-result="on">测试组件<em>类</em>就像测试服务那样简单。</p><p translation-origin="off">Testing the component <em>class</em> is as easy as testing a service.</p><p translation-result="on">但组件不仅是这个类。 组件还要和 DOM 以及其它组件进行交互。 <em>只涉及类</em>的测试可以告诉你组件类的行为是否正常， 但是不能告诉你组件是否能正常渲染出来、响应用户的输入和查询或与它的父组件和子组件相集成。</p><p translation-origin="off">But a component is more than just its class. A component interacts with the DOM and with other components. The <em>class-only</em> tests can tell you about class behavior. They cannot tell you if the component is going to render properly, respond to user input and gestures, or integrate with its parent and child components.</p><p translation-result="on">上述<em>只涉及类</em>的测试没办法回答这些组件在屏幕上的行为之类的关键性问题：</p><p translation-origin="off">None of the <em>class-only</em> tests above can answer key questions about how the components actually behave on screen.</p><ul><li><p translation-result="on"> <code>Lightswitch.clicked()</code> 是否真的绑定到了某些用户可以接触到的东西？</p><p translation-origin="off">Is <code>Lightswitch.clicked()</code> bound to anything such that the user can invoke it?</p></li><li><p translation-result="on"> <code>Lightswitch.message</code> 是否真的显示出来了？</p><p translation-origin="off">Is the <code>Lightswitch.message</code> displayed?</p></li><li><p translation-result="on">用户真的可以选择 <code>DashboardHeroComponent</code> 中显示的某个英雄吗？</p><p translation-origin="off">Can the user actually select the hero displayed by <code>DashboardHeroComponent</code>?</p></li><li><p translation-result="on">英雄的名字是否如预期般显示出来了？（比如是否大写）</p><p translation-origin="off">Is the hero name displayed as expected (i.e, in uppercase)?</p></li><li><p translation-result="on"> <code>WelcomeComponent</code> 的模板是否显示了欢迎信息？</p><p translation-origin="off">Is the welcome message displayed by the template of <code>WelcomeComponent</code>?</p></li></ul><p translation-result="on">这些问题对于上面这种简单的组件来说当然没有问题， 不过很多组件和它们模板中所描述的 DOM 元素之间会有复杂的交互，当组件的状态发生变化时，会导致一些 HTML 出现和消失。</p><p translation-origin="off">These may not be troubling questions for the simple components illustrated above. But many components have complex interactions with the DOM elements described in their templates, causing HTML to appear and disappear as the component state changes.</p><p translation-result="on">要回答这类问题，你就不得不创建那些与组件相关的 DOM 元素了，你必须检查 DOM 来确认组件的状态能在恰当的时机正常显示出来，并且必须通过屏幕来仿真用户的交互，以判断这些交互是否如预期的那般工作。</p><p translation-origin="off">To answer these kinds of questions, you have to create the DOM elements associated with the components, you must examine the DOM to confirm that component state displays properly at the appropriate times, and you must simulate user interaction with the screen to determine whether those interactions cause the component to behave as expected.</p><p translation-result="on">要想写这类测试，你就要用到 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 的附加功能以及其它测试助手了。</p><p translation-origin="off">To write these kinds of test, you'll use additional features of the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> as well as other testing helpers.</p><h4 id="cli-generated-tests" translation-result="on">CLI 生成的测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#cli-generated-tests"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="cli-generated-tests">CLI-generated tests<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#cli-generated-tests"><i class="material-icons">link</i></a></h4><p translation-result="on">当你用 CLI 生成新的组件时，它也会默认创建最初的测试文件。</p><p translation-origin="off">The CLI creates an initial test file for you by default when you ask it to generate a new component.</p><p translation-result="on">比如，下列 CLI 命令会在 <code>app/banner</code> 文件夹中生成带有内联模板和内联样式的 <code>BannerComponent</code>：</p><p translation-origin="off">For example, the following CLI command generates a <code>BannerComponent</code> in the <code>app/banner</code> folder (with inline template and styles):</p><code-example language="sh" class="code-shell" ng-version="9.0.0-rc.11"><div style="display:none">ng generate component banner --inline-template --inline-style --module app</div><aio-code><pre class="lang-sh prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">ng generate component banner </span><span class="pun">--</span><span class="pln">inline</span><span class="pun">-</span><span class="pln">template </span><span class="pun">--</span><span class="pln">inline</span><span class="pun">-</span><span class="pln">style </span><span class="pun">--</span><span class="pln">module app</span></code>
    </pre></aio-code></code-example><p translation-result="on">它也会为组件生成最初的测试文件 <code>banner-external.component.spec.ts</code>，代码如下：</p><p translation-origin="off">It also generates an initial test file for the component, <code>banner-external.component.spec.ts</code>, that looks like this:</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="v1" header="app/banner/banner-external.component.spec.ts (initial)" ng-version="9.0.0-rc.11"><div style="display:none">import { <a href="api/core/testing/async" class="code-anchor">async</a>, <a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a>, <a href="api/core/testing/TestBed" class="code-anchor">TestBed</a> } from '@angular/core/testing'; import { BannerComponent } from './banner.component'; describe('BannerComponent', () =&gt; { let component: BannerComponent; let fixture: <a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a>&lt;BannerComponent&gt;; beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { TestBed.configureTestingModule({ declarations: [ BannerComponent ] }) .compileComponents(); })); beforeEach(() =&gt; { fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () =&gt; { expect(component).toBeDefined(); }); });</div><header class="ng-star-inserted">app/banner/banner-external.component.spec.ts (initial)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner-external.component.spec.ts (initial)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/ComponentFixture" class="code-anchor"><span class="typ">ComponentFixture</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/TestBed" class="code-anchor"><span class="typ">TestBed</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core/testing'</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'./banner.component'</span><span class="pun">;</span><span class="pln">

describe</span><span class="pun">(</span><span class="str">'BannerComponent'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> component</span><span class="pun">:</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> fixture</span><span class="pun">:</span><span class="pln"> </span><a href="api/core/testing/ComponentFixture" class="code-anchor"><span class="typ">ComponentFixture</span></a><span class="pun">&lt;</span><span class="typ">BannerComponent</span><span class="pun">&gt;;</span><span class="pln">

  beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
      declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
    </span><span class="pun">})</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">compileComponents</span><span class="pun">();</span><span class="pln">
  </span><span class="pun">}));</span><span class="pln">

  beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">BannerComponent</span><span class="pun">);</span><span class="pln">
    component </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">
    fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'should create'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">component</span><span class="pun">).</span><span class="pln">toBeDefined</span><span class="pun">();</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><div class="alert is-helpful"><p translation-result="on">由于 <code>compileComponents</code> 是异步的，所以它要使用从 <code>@angular/core/testing</code> 中导入的工具函数 <a href="api/core/testing/async"><code>async</code></a>。</p><p translation-origin="off">Because <code>compileComponents</code> is asynchronous, it uses the <a href="api/core/testing/async"><code>async</code></a>utility function imported from <code>@angular/core/testing</code>.</p><p translation-result="on">欲知详情，请参见 <a href="guide/testing#async">async</a> 部分。</p><p translation-origin="off">Please refer to the <a href="guide/testing#async">async</a> section for more details.</p></div><h4 id="reduce-the-setup" translation-result="on">缩减环境准备代码<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#reduce-the-setup"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="reduce-the-setup">Reduce the setup<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#reduce-the-setup"><i class="material-icons">link</i></a></h4><p translation-result="on">这个文件中只有最后三行是真正测试组件的，它们用来断言 Angular 可以创建该组件。</p><p translation-origin="off">Only the last three lines of this file actually test the component and all they do is assert that Angular can create the component.</p><p translation-result="on">文件的其它部分都是为更高级的测试二准备的样板代码，当组件逐渐演变成更加实质性的东西时，它们才<em>可能</em>变成必备的。</p><p translation-origin="off">The rest of the file is boilerplate setup code anticipating more advanced tests that <em>might</em> become necessary if the component evolves into something substantial.</p><p translation-result="on">稍后你将学到这些高级的测试特性。 不过目前，你可以先把这些测试文件缩减成更加可控的大小，以便理解：</p><p translation-origin="off">You'll learn about these advanced test features below. For now, you can radically reduce this test file to a more manageable size:</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="v2" header="app/banner/banner-initial.component.spec.ts (minimal)" ng-version="9.0.0-rc.11"><div style="display:none">describe('BannerComponent (minimal)', () =&gt; { it('should create', () =&gt; { TestBed.configureTestingModule({ declarations: [ BannerComponent ] }); const fixture = TestBed.createComponent(BannerComponent); const component = fixture.componentInstance; expect(component).toBeDefined(); }); });</div><header class="ng-star-inserted">app/banner/banner-initial.component.spec.ts (minimal)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner-initial.component.spec.ts (minimal)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">describe</span><span class="pun">(</span><span class="str">'BannerComponent (minimal)'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  it</span><span class="pun">(</span><span class="str">'should create'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
      declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
    </span><span class="pun">});</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">BannerComponent</span><span class="pun">);</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> component </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">component</span><span class="pun">).</span><span class="pln">toBeDefined</span><span class="pun">();</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">在这个例子中，传给 <code>TestBed.configureTestingModule</code> 的元数据对象中只声明了 <code>BannerComponent</code> —— 待测试的组件。</p><p translation-origin="off">In this example, the metadata object passed to <code>TestBed.configureTestingModule</code> simply declares <code>BannerComponent</code>, the component to test.</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="configureTestingModule" ng-version="9.0.0-rc.11"><div style="display:none">TestBed.configureTestingModule({ declarations: [ BannerComponent ] });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
  declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><div class="alert is-helpful"><p translation-result="on">不用声明或导入任何其它的东西。 默认的测试模块中已经预先配置好了一些东西，比如来自 <code>@angular/platform-browser</code> 的 <code><a href="api/platform-browser/BrowserModule" class="code-anchor">BrowserModule</a></code>。</p><p translation-origin="off">There's no need to declare or import anything else. The default test module is pre-configured with something like the <code><a href="api/platform-browser/BrowserModule" class="code-anchor">BrowserModule</a></code> from <code>@angular/platform-browser</code>.</p><p translation-result="on">稍后你将会调用带有导入模块、服务提供商和更多可声明对象的 <code>TestBed.configureTestingModule()</code> 来满足测试所需。 将来还可以用可选的 <code>override</code> 方法对这些配置进行微调。</p><p translation-origin="off">Later you'll call <code>TestBed.configureTestingModule()</code> with imports, providers, and more declarations to suit your testing needs. Optional <code>override</code> methods can further fine-tune aspects of the configuration.</p></div><a id="create-component"></a><h4 id="createcomponent"><em>createComponent()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#createcomponent"><i class="material-icons">link</i></a></h4><p translation-result="on">在配置好 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 之后，你还可以调用它的 <code>createComponent()</code> 方法。</p><p translation-origin="off">After configuring <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>, you call its <code>createComponent()</code> method.</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="createComponent" ng-version="9.0.0-rc.11"><div style="display:none">const fixture = TestBed.createComponent(BannerComponent);</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">const</span><span class="pln"> fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">BannerComponent</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>TestBed.createComponent()</code> 会创建一个 <code>BannerComponent</code> 的实例，把相应的元素添加到测试运行器的 DOM 中，然后返回一个 <a href="guide/testing#component-fixture"><code>ComponentFixture</code></a>对象。</p><p translation-origin="off"><code>TestBed.createComponent()</code> creates an instance of the <code>BannerComponent</code>, adds a corresponding element to the test-runner DOM, and returns a <a href="guide/testing#component-fixture"><code>ComponentFixture</code></a>.</p><div class="alert is-important"><p translation-result="on">在调用了 <code>createComponent</code> 之后就不能再重新配置 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 了。</p><p translation-origin="off">Do not re-configure <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> after calling <code>createComponent</code>.</p><p translation-result="on"><code>createComponent</code> 方法冻结了当前的 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 定义，关闭它才能再进行后续配置。</p><p translation-origin="off">The <code>createComponent</code> method freezes the current <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> definition, closing it to further configuration.</p><p translation-result="on">你不能再调用任何 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 的后续配置方法了，不能调 <code>configureTestingModule()</code>、不能调 <code>get()</code>， 也不能调用任何 <code>override...</code> 方法。 如果试图这么做，<code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 就会抛出错误。</p><p translation-origin="off">You cannot call any more <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> configuration methods, not <code>configureTestingModule()</code>, nor <code>get()</code>, nor any of the <code>override...</code> methods. If you try, <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> throws an error.</p></div><a id="component-fixture"></a><h4 id="componentfixture"><em>ComponentFixture</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#componentfixture"><i class="material-icons">link</i></a></h4><p translation-result="on"><a href="api/core/testing/ComponentFixture">ComponentFixture</a> 是一个测试挽具（就像马车缰绳），用来与所创建的组件及其 DOM 元素进行交互。</p><p translation-origin="off">The <a href="api/core/testing/ComponentFixture">ComponentFixture</a> is a test harness for interacting with the created component and its corresponding element.</p><p translation-result="on">可以通过测试夹具（fixture）来访问该组件的实例，并用 Jasmine 的 <code>expect</code> 语句来确保其存在。</p><p translation-origin="off">Access the component instance through the fixture and confirm it exists with a Jasmine expectation:</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="componentInstance" ng-version="9.0.0-rc.11"><div style="display:none">const component = fixture.componentInstance; expect(component).toBeDefined();</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">const</span><span class="pln"> component </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">
expect</span><span class="pun">(</span><span class="pln">component</span><span class="pun">).</span><span class="pln">toBeDefined</span><span class="pun">();</span></code>
    </pre></aio-code></code-example><h4 id="beforeeach"><em>beforeEach()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#beforeeach"><i class="material-icons">link</i></a></h4><p translation-result="on">随着该组件的成长，你将会添加更多测试。 除了为每个测试都复制一份 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 测试之外，你还可以把它们重构成 Jasmine 的 <code>beforeEach()</code> 中的准备语句以及一些支持性变量：</p><p translation-origin="off">You will add more tests as this component evolves. Rather than duplicate the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> configuration for each test, you refactor to pull the setup into a Jasmine <code>beforeEach()</code> and some supporting variables:</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="v3" ng-version="9.0.0-rc.11"><div style="display:none">describe('BannerComponent (with beforeEach)', () =&gt; { let component: BannerComponent; let fixture: <a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a>&lt;BannerComponent&gt;; beforeEach(() =&gt; { TestBed.configureTestingModule({ declarations: [ BannerComponent ] }); fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; }); it('should create', () =&gt; { expect(component).toBeDefined(); }); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">describe</span><span class="pun">(</span><span class="str">'BannerComponent (with beforeEach)'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> component</span><span class="pun">:</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> fixture</span><span class="pun">:</span><span class="pln"> </span><a href="api/core/testing/ComponentFixture" class="code-anchor"><span class="typ">ComponentFixture</span></a><span class="pun">&lt;</span><span class="typ">BannerComponent</span><span class="pun">&gt;;</span><span class="pln">

  beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
      declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
    </span><span class="pun">});</span><span class="pln">
    fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">BannerComponent</span><span class="pun">);</span><span class="pln">
    component </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'should create'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">component</span><span class="pun">).</span><span class="pln">toBeDefined</span><span class="pun">();</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">现在，添加一个测试，用它从 <code>fixture.nativeElement</code> 中获取组件的元素，并查找是否存在所预期的文本内容。</p><p translation-origin="off">Now add a test that gets the component's element from <code>fixture.nativeElement</code> and looks for the expected text.</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="v4-test-2" ng-version="9.0.0-rc.11"><div style="display:none">it('should contain "banner works!"', () =&gt; { const bannerElement: HTMLElement = fixture.nativeElement; expect(bannerElement.textContent).toContain('banner works!'); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should contain "banner works!"'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> bannerElement</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">;</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">bannerElement</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="str">'banner works!'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><a id="native-element"></a><h4 id="nativeelement"><em>nativeElement</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#nativeelement"><i class="material-icons">link</i></a></h4><p translation-result="on"><code><a href="api/core/testing/ComponentFixture#nativeElement" class="code-anchor">ComponentFixture.nativeElement</a></code> 的值是 <code>any</code> 类型的。 稍后你将遇到的 <code><a href="api/core/DebugElement#nativeElement" class="code-anchor">DebugElement.nativeElement</a></code> 也同样是 <code>any</code> 类型的。</p><p translation-origin="off">The value of <code><a href="api/core/testing/ComponentFixture#nativeElement" class="code-anchor">ComponentFixture.nativeElement</a></code> has the <code>any</code> type. Later you'll encounter the <code><a href="api/core/DebugElement#nativeElement" class="code-anchor">DebugElement.nativeElement</a></code> and it too has the <code>any</code> type.</p><p translation-result="on">Angular 在编译期间没办法知道 <code>nativeElement</code> 是哪种 HTML 元素，甚至是否 HTML 元素（译注：比如可能是 SVG 元素）。 本应用还可能运行在<em>非浏览器平台上</em>，比如服务端渲染或 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Worker</a> 那里的元素可能只有一些缩水过的 API，甚至根本不存在。</p><p translation-origin="off">Angular can't know at compile time what kind of HTML element the <code>nativeElement</code> is or if it even is an HTML element. The app might be running on a <em>non-browser platform</em>, such as the server or a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Worker</a>, where the element may have a diminished API or not exist at all.</p><p translation-result="on">本指南中的测试都是为运行在浏览器中而设计的，因此 <code>nativeElement</code> 的值一定会是 <code>HTMLElement</code> 或其派生类。</p><p translation-origin="off">The tests in this guide are designed to run in a browser so a <code>nativeElement</code> value will always be an <code>HTMLElement</code> or one of its derived classes.</p><p translation-result="on">如果知道了它是某种 <code>HTMLElement</code>，你就可以用标准的 <code>querySelector</code> 在元素树中进行深挖了。</p><p translation-origin="off">Knowing that it is an <code>HTMLElement</code> of some sort, you can use the standard HTML <code>querySelector</code> to dive deeper into the element tree.</p><p translation-result="on">下面这个测试就会调用 <code>HTMLElement.querySelector</code> 来获取 <code>&lt;p&gt;</code> 元素，并在其中查找 Banner 文本：</p><p translation-origin="off">Here's another test that calls <code>HTMLElement.querySelector</code> to get the paragraph element and look for the banner text:</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="v4-test-3" ng-version="9.0.0-rc.11"><div style="display:none">it('should have &lt;p&gt; with "banner works!"', () =&gt; { const bannerElement: HTMLElement = fixture.nativeElement; const p = bannerElement.querySelector('p'); expect(p.textContent).toEqual('banner works!'); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should have &lt;p&gt; with "banner works!"'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> bannerElement</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> p </span><span class="pun">=</span><span class="pln"> bannerElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'p'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">p</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toEqual</span><span class="pun">(</span><span class="str">'banner works!'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><a id="debug-element"></a><h4 id="debugelement"><em>DebugElement</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#debugelement"><i class="material-icons">link</i></a></h4><p translation-result="on">Angular 的<em>夹具</em>可以通过 <code>fixture.nativeElement</code> 直接提供组件的元素。</p><p translation-origin="off">The Angular <em>fixture</em> provides the component's element directly through the <code>fixture.nativeElement</code>.</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="nativeElement" ng-version="9.0.0-rc.11"><div style="display:none">const bannerElement: HTMLElement = fixture.nativeElement;</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">const</span><span class="pln"> bannerElement</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">;</span></code>
    </pre></aio-code></code-example><p translation-result="on">它实际上是 <code>fixture.debugElement.nativeElement</code> 的一个便利方法。</p><p translation-origin="off">This is actually a convenience method, implemented as <code>fixture.debugElement.nativeElement</code>.</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="debugElement-nativeElement" ng-version="9.0.0-rc.11"><div style="display:none">const bannerDe: <a href="api/core/DebugElement" class="code-anchor">DebugElement</a> = fixture.debugElement; const bannerEl: HTMLElement = bannerDe.nativeElement;</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">const</span><span class="pln"> bannerDe</span><span class="pun">:</span><span class="pln"> </span><a href="api/core/DebugElement" class="code-anchor"><span class="typ">DebugElement</span></a><span class="pln"> </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">const</span><span class="pln"> bannerEl</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> bannerDe</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">;</span></code>
    </pre></aio-code></code-example><p translation-result="on">这种访问元素的迂回方式有很好的理由。</p><p translation-origin="off">There's a good reason for this circuitous path to the element.</p><p translation-result="on"><code>nativeElement</code> 的属性取决于运行环境。 你可以在没有 DOM，或者其 DOM 模拟器无法支持全部 <code>HTMLElement</code> API 的平台上运行这些测试。</p><p translation-origin="off">The properties of the <code>nativeElement</code> depend upon the runtime environment. You could be running these tests on a <em>non-browser</em> platform that doesn't have a DOM or whose DOM-emulation doesn't support the full <code>HTMLElement</code> API.</p><p translation-result="on">Angular 依赖于 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 这个抽象层，就可以安全的横跨<em>其支持的所有平台</em>。 Angular 不再创建 HTML 元素树，而是创建 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 树，其中包裹着相应运行平台上的<em>原生元素</em>。 <code>nativeElement</code> 属性会解开 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code>，并返回平台相关的元素对象。</p><p translation-origin="off">Angular relies on the <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> abstraction to work safely across <em>all supported platforms</em>. Instead of creating an HTML element tree, Angular creates a <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> tree that wraps the <em>native elements</em> for the runtime platform. The <code>nativeElement</code> property unwraps the <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> and returns the platform-specific element object.</p><p translation-result="on">因为本章的这些测试都设计为只运行在浏览器中，因此这些测试中的 <code>nativeElement</code> 总是 <code>HTMLElement</code>， 你可以在测试中使用那些熟悉的方法和属性进行浏览。</p><p translation-origin="off">Because the sample tests for this guide are designed to run only in a browser, a <code>nativeElement</code> in these tests is always an <code>HTMLElement</code> whose familiar methods and properties you can explore within a test.</p><p translation-result="on">下面是对上一个测试改用 <code>fixture.debugElement.nativeElement</code> 进行的重新实现：</p><p translation-origin="off">Here's the previous test, re-implemented with <code>fixture.debugElement.nativeElement</code>:</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="v4-test-4" ng-version="9.0.0-rc.11"><div style="display:none">it('should find the &lt;p&gt; with fixture.debugElement.nativeElement)', () =&gt; { const bannerDe: <a href="api/core/DebugElement" class="code-anchor">DebugElement</a> = fixture.debugElement; const bannerEl: HTMLElement = bannerDe.nativeElement; const p = bannerEl.querySelector('p'); expect(p.textContent).toEqual('banner works!'); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should find the &lt;p&gt; with fixture.debugElement.nativeElement)'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> bannerDe</span><span class="pun">:</span><span class="pln"> </span><a href="api/core/DebugElement" class="code-anchor"><span class="typ">DebugElement</span></a><span class="pln"> </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> bannerEl</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> bannerDe</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> p </span><span class="pun">=</span><span class="pln"> bannerEl</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'p'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">p</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toEqual</span><span class="pun">(</span><span class="str">'banner works!'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 还有其它的方法和属性，它们在测试中也很有用，你将在本章的其它测试中看到它们。</p><p translation-origin="off">The <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> has other methods and properties that are useful in tests, as you'll see elsewhere in this guide.</p><p translation-result="on">你要从 Angular 核心库中导入 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 符号。</p><p translation-origin="off">You import the <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> symbol from the Angular core library.</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="import-debug-element" ng-version="9.0.0-rc.11"><div style="display:none">import { <a href="api/core/DebugElement" class="code-anchor">DebugElement</a> } from '@angular/core';</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/DebugElement" class="code-anchor"><span class="typ">DebugElement</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core'</span><span class="pun">;</span></code>
    </pre></aio-code></code-example><a id="by-css"></a><h4 id="bycss"><em>By.css()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#bycss"><i class="material-icons">link</i></a></h4><p translation-result="on">虽然本章中的测试都是运行在浏览器中的，不过有些应用可能会运行在其它平台上（至少一部分时间是这样）。</p><p translation-origin="off">Although the tests in this guide all run in the browser, some apps might run on a different platform at least some of the time.</p><p translation-result="on">比如，作为加快慢速网络设备上应用启动速度的一种策略，组件可能要先在服务器上渲染。服务端渲染可能无法支持完全的 HTML API。 如果它不支持 <code>querySelector</code>，那么前一个测试就会失败。</p><p translation-origin="off">For example, the component might render first on the server as part of a strategy to make the application launch faster on poorly connected devices. The server-side renderer might not support the full HTML element API. If it doesn't support <code>querySelector</code>, the previous test could fail.</p><p translation-result="on"><code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 提供了可以工作在所有受支持的平台上的查询方法。 这些查询方法接受一个谓词（predicate）函数，如果 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 树中的节点满足某个筛选条件，它就返回 <code>true</code>。</p><p translation-origin="off">The <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> offers query methods that work for all supported platforms. These query methods take a <em>predicate</em> function that returns <code>true</code> when a node in the <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> tree matches the selection criteria.</p><p translation-result="on">你可以在从库中导入的 <code><a href="api/platform-browser/By" class="code-anchor">By</a></code> 类的帮助下为该运行平台创建谓词函数。下面这个 <code><a href="api/platform-browser/By" class="code-anchor">By</a></code> 是从浏览器平台导入的：</p><p translation-origin="off">You create a <em>predicate</em> with the help of a <code><a href="api/platform-browser/By" class="code-anchor">By</a></code> class imported from a library for the runtime platform. Here's the <code><a href="api/platform-browser/By" class="code-anchor">By</a></code> import for the browser platform:</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="import-by" ng-version="9.0.0-rc.11"><div style="display:none">import { <a href="api/platform-browser/By" class="code-anchor">By</a> } from '@angular/platform-browser';</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/platform-browser/By" class="code-anchor"><span class="typ">By</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/platform-browser'</span><span class="pun">;</span></code>
    </pre></aio-code></code-example><p translation-result="on">下面这个例子使用 <code>DebugElement.query()</code> 和浏览器的 <code>By.css</code> 方法重新实现了前一个测试。</p><p translation-origin="off">The following example re-implements the previous test with <code>DebugElement.query()</code> and the browser's <code>By.css</code> method.</p><code-example path="testing/src/app/banner/banner-initial.component.spec.ts" region="v4-test-5" ng-version="9.0.0-rc.11"><div style="display:none">it('should find the &lt;p&gt; with fixture.debugElement.query(By.css)', () =&gt; { const bannerDe: <a href="api/core/DebugElement" class="code-anchor">DebugElement</a> = fixture.debugElement; const paragraphDe = bannerDe.query(By.css('p')); const p: HTMLElement = paragraphDe.nativeElement; expect(p.textContent).toEqual('banner works!'); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should find the &lt;p&gt; with fixture.debugElement.query(By.css)'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> bannerDe</span><span class="pun">:</span><span class="pln"> </span><a href="api/core/DebugElement" class="code-anchor"><span class="typ">DebugElement</span></a><span class="pln"> </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> paragraphDe </span><span class="pun">=</span><span class="pln"> bannerDe</span><span class="pun">.</span><span class="pln">query</span><span class="pun">(</span><span class="typ">By</span><span class="pun">.</span><span class="pln">css</span><span class="pun">(</span><span class="str">'p'</span><span class="pun">));</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> p</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> paragraphDe</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">;</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">p</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toEqual</span><span class="pun">(</span><span class="str">'banner works!'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">值得注意的地方有：</p><p translation-origin="off">Some noteworthy observations:</p><ul><li><p translation-result="on"> <code><a href="api/platform-browser/By#css" class="code-anchor">By.css()</a></code> 静态方法使用<a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors" title="CSS selectors">标准 CSS 选择器</a>选择了一些 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 节点。</p><p translation-origin="off">The <code><a href="api/platform-browser/By#css" class="code-anchor">By.css()</a></code> static method selects <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> nodes with a <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors" title="CSS selectors">standard CSS selector</a>.</p></li><li><p translation-result="on">这次查询返回了 <code>&lt;p&gt;</code> 元素的一个 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code>。</p><p translation-origin="off">The query returns a <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> for the paragraph.</p></li><li><p translation-result="on">你必须解包此结果，以获取这个 <code>&lt;p&gt;</code> 元素。</p><p translation-origin="off">You must unwrap that result to get the paragraph element.</p></li></ul><p translation-result="on">当你要通过 CSS 选择器过滤，并且只打算测试浏览器的<em>原生元素</em>的属性时，<code>By.css</code> 这种方法就有点多余了。</p><p translation-origin="off">When you're filtering by CSS selector and only testing properties of a browser's <em>native element</em>, the <code>By.css</code> approach may be overkill.</p><p translation-result="on">使用标准的 <code>HTMLElement</code> 方法，比如 <code>querySelector()</code> 或 <code>querySelectorAll()</code> 通常会更简单、更清晰。 你在下一组测试中就会体会到这一点。</p><p translation-origin="off">It's often easier and more clear to filter with a standard <code>HTMLElement</code> method such as <code>querySelector()</code> or <code>querySelectorAll()</code>, as you'll see in the next set of tests.</p><hr><h2 id="component-test-scenarios" translation-result="on">组件测试场景<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-test-scenarios"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="component-test-scenarios">Component Test Scenarios<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-test-scenarios"><i class="material-icons">link</i></a></h2><p translation-result="on">下面这些部分构成了本指南的大部分内容，它们将探讨一些常见的组件测试场景。</p><p translation-origin="off">The following sections, comprising most of this guide, explore common component testing scenarios</p><h3 id="component-binding" translation-result="on">组件绑定<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-binding"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="component-binding">Component binding<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-binding"><i class="material-icons">link</i></a></h3><p translation-result="on">当前的 <code>BannerComponent</code> 在 HTML 模板中展示了静态标题内容。</p><p translation-origin="off">The current <code>BannerComponent</code> presents static title text in the HTML template.</p><p translation-result="on">稍作修改之后，<code>BannerComponent</code> 也可以通过绑定到组件的 <code>title</code> 属性来展示动态标题。就像这样：</p><p translation-origin="off">After a few changes, the <code>BannerComponent</code> presents a dynamic title by binding to the component's <code>title</code> property like this.</p><code-example path="testing/src/app/banner/banner.component.ts" region="component" header="app/banner/banner.component.ts" ng-version="9.0.0-rc.11"><div style="display:none">@<a href="api/core/Component" class="code-anchor">Component</a>({ selector: 'app-banner', template: '&lt;h1&gt;{{title}}&lt;/h1&gt;', styles: ['h1 { color: green; font-size: 350%}'] }) export class BannerComponent { title = 'Test Tour of Heroes'; }</div><header class="ng-star-inserted">app/banner/banner.component.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner.component.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">
  selector</span><span class="pun">:</span><span class="pln"> </span><span class="str">'app-banner'</span><span class="pun">,</span><span class="pln">
  </span><span class="kwd">template</span><span class="pun">:</span><span class="pln"> </span><span class="str">'&lt;h1&gt;{{title}}&lt;/h1&gt;'</span><span class="pun">,</span><span class="pln">
  styles</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="str">'h1 { color: green; font-size: 350%}'</span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  title </span><span class="pun">=</span><span class="pln"> </span><span class="str">'Test Tour of Heroes'</span><span class="pun">;</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">很简单，你决定添加一个测试来确定这个组件真的像你预期的那样显示出了正确的内容。</p><p translation-origin="off">Simple as this is, you decide to add a test to confirm that component actually displays the right content where you think it should.</p><h4 id="query-for-the-h1" translation-result="on">查询 <code>&lt;h1&gt;</code><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#query-for-the-h1"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="query-for-the-h1">Query for the <em>&lt;h1&gt;</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#query-for-the-h1"><i class="material-icons">link</i></a></h4><p translation-result="on">你将会写一系列测试来探查 <code>&lt;h1&gt;</code> 元素的值，这个值包含在了带有 <code>title</code> 属性的插值绑定中。</p><p translation-origin="off">You'll write a sequence of tests that inspect the value of the <code>&lt;h1&gt;</code> element that wraps the <em>title</em> property interpolation binding.</p><p translation-result="on">你要修改 <code>beforeEach</code> 来使用标准的 HTML <code>querySelector</code> 来找到该元素，并把它赋值给 <code>h1</code> 变量。</p><p translation-origin="off">You update the <code>beforeEach</code> to find that element with a standard HTML <code>querySelector</code> and assign it to the <code>h1</code> variable.</p><code-example path="testing/src/app/banner/banner.component.spec.ts" region="setup" header="app/banner/banner.component.spec.ts (setup)" ng-version="9.0.0-rc.11"><div style="display:none">let component: BannerComponent; let fixture: <a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a>&lt;BannerComponent&gt;; let h1: HTMLElement; beforeEach(() =&gt; { TestBed.configureTestingModule({ declarations: [ BannerComponent ], }); fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; // BannerComponent test instance h1 = fixture.nativeElement.querySelector('h1'); });</div><header class="ng-star-inserted">app/banner/banner.component.spec.ts (setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner.component.spec.ts (setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">let</span><span class="pln"> component</span><span class="pun">:</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">let</span><span class="pln"> fixture</span><span class="pun">:</span><span class="pln">   </span><a href="api/core/testing/ComponentFixture" class="code-anchor"><span class="typ">ComponentFixture</span></a><span class="pun">&lt;</span><span class="typ">BannerComponent</span><span class="pun">&gt;;</span><span class="pln">
</span><span class="kwd">let</span><span class="pln"> h1</span><span class="pun">:</span><span class="pln">        </span><span class="typ">HTMLElement</span><span class="pun">;</span><span class="pln">

beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
  fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">BannerComponent</span><span class="pun">);</span><span class="pln">
  component </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln"> </span><span class="com">// BannerComponent test instance</span><span class="pln">
  h1 </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'h1'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><a id="detect-changes"></a><h4 id="createcomponent-does-not-bind-data" translation-result="on"><code>createComponent()</code> 函数不会绑定数据<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#createcomponent-does-not-bind-data"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="createcomponent-does-not-bind-data"><em>createComponent()</em> does not bind data<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#createcomponent-does-not-bind-data"><i class="material-icons">link</i></a></h4><p translation-result="on">你的第一个测试希望看到屏幕显示出了默认的 <code>title</code>。 你本能的写出如下测试来立即审查这个 <code>&lt;h1&gt;</code> 元素：</p><p translation-origin="off">For your first test you'd like to see that the screen displays the default <code>title</code>. Your instinct is to write a test that immediately inspects the <code>&lt;h1&gt;</code> like this:</p><code-example path="testing/src/app/banner/banner.component.spec.ts" region="expect-h1-default-v1" ng-version="9.0.0-rc.11"><div style="display:none">it('should display original title', () =&gt; { expect(h1.textContent).toContain(component.title); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should display original title'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">h1</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="pln">component</span><span class="pun">.</span><span class="pln">title</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">但<em>测试失败了</em>，给出如下信息：</p><p translation-origin="off"><em>That test fails</em> with the message:</p><code-example language="javascript" ng-version="9.0.0-rc.11"><div style="display:none">expected '' to contain 'Test Tour of Heroes'.</div><aio-code><pre class="lang-javascript prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">expected </span><span class="str">''</span><span class="pln"> to contain </span><span class="str">'Test Tour of Heroes'</span><span class="pun">.</span></code>
    </pre></aio-code></code-example><p translation-result="on">因为绑定是在 Angular 执行<strong>变更检测</strong>时才发生的。</p><p translation-origin="off">Binding happens when Angular performs <strong>change detection</strong>.</p><p translation-result="on">在产品阶段，当 Angular 创建组件、用户输入或者异步动作（比如 AJAX）完成时，会自动触发变更检测。</p><p translation-origin="off">In production, change detection kicks in automatically when Angular creates a component or the user enters a keystroke or an asynchronous activity (e.g., AJAX) completes.</p><p translation-result="on">但 <code>TestBed.createComponent</code> <em>不能</em>触发变更检测。 可以在这个修改后的测试中确定这一点：</p><p translation-origin="off">The <code>TestBed.createComponent</code> does <em>not</em> trigger change detection. a fact confirmed in the revised test:</p><code-example path="testing/src/app/banner/banner.component.spec.ts" region="test-w-o-detect-changes" ng-version="9.0.0-rc.11"><div style="display:none">it('no title in the DOM after createComponent()', () =&gt; { expect(h1.textContent).toEqual(''); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'no title in the DOM after createComponent()'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">h1</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toEqual</span><span class="pun">(</span><span class="str">''</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><h4 id="detectchanges"><em>detectChanges()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#detectchanges"><i class="material-icons">link</i></a></h4><p translation-result="on">你必须通过调用 <code>fixture.detectChanges()</code> 来要求 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 执行数据绑定。 然后 <code>&lt;h1&gt;</code> 中才会具有所期望的标题。</p><p translation-origin="off">You must tell the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> to perform data binding by calling <code>fixture.detectChanges()</code>. Only then does the <code>&lt;h1&gt;</code> have the expected title.</p><code-example path="testing/src/app/banner/banner.component.spec.ts" region="expect-h1-default" ng-version="9.0.0-rc.11"><div style="display:none">it('should display original title after detectChanges()', () =&gt; { fixture.detectChanges(); expect(h1.textContent).toContain(component.title); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should display original title after detectChanges()'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">h1</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="pln">component</span><span class="pun">.</span><span class="pln">title</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">这种迟到的变更检测是故意设计的，而且很有用。 它给了测试者一个机会，<em>在 Angular 初始化数据绑定以及调用<a href="guide/lifecycle-hooks">生命周期钩子</a>之前</em>探查并改变组件的状态。</p><p translation-origin="off">Delayed change detection is intentional and useful. It gives the tester an opportunity to inspect and change the state of the component <em>before Angular initiates data binding and calls <a href="guide/lifecycle-hooks">lifecycle hooks</a></em>.</p><p translation-result="on">下面这个测试中，会在调用 <code>fixture.detectChanges()</code> <em>之前</em>修改组件的 <code>title</code> 属性。</p><p translation-origin="off">Here's another test that changes the component's <code>title</code> property <em>before</em> calling <code>fixture.detectChanges()</code>.</p><code-example path="testing/src/app/banner/banner.component.spec.ts" region="after-change" ng-version="9.0.0-rc.11"><div style="display:none">it('should display a different test title', () =&gt; { component.title = 'Test <a href="api/platform-browser/Title" class="code-anchor">Title</a>'; fixture.detectChanges(); expect(h1.textContent).toContain('Test <a href="api/platform-browser/Title" class="code-anchor">Title</a>'); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should display a different test title'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  component</span><span class="pun">.</span><span class="pln">title </span><span class="pun">=</span><span class="pln"> </span><span class="str">'Test </span><a href="api/platform-browser/Title" class="code-anchor"><span class="str">Title</span></a><span class="str">'</span><span class="pun">;</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">h1</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="str">'Test </span><a href="api/platform-browser/Title" class="code-anchor"><span class="str">Title</span></a><span class="str">'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><a id="auto-detect-changes"></a><h4 id="automatic-change-detection" translation-result="on">自动变更检测<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#automatic-change-detection"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="automatic-change-detection">Automatic change detection<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#automatic-change-detection"><i class="material-icons">link</i></a></h4><p translation-result="on"><code>BannerComponent</code> 的这些测试需要频繁调用 <code>detectChanges</code>。 有些测试者更喜欢让 Angular 测试环境自动运行变更检测。</p><p translation-origin="off">The <code>BannerComponent</code> tests frequently call <code>detectChanges</code>. Some testers prefer that the Angular test environment run change detection automatically.</p><p translation-result="on">使用 <code><a href="api/core/testing/ComponentFixtureAutoDetect" class="code-anchor">ComponentFixtureAutoDetect</a></code> 服务提供商来配置 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 就可以做到这一点。 首先从测试工具库中导入它：</p><p translation-origin="off">That's possible by configuring the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> with the <code><a href="api/core/testing/ComponentFixtureAutoDetect" class="code-anchor">ComponentFixtureAutoDetect</a></code> provider. First import it from the testing utility library:</p><code-example path="testing/src/app/banner/banner.component.detect-changes.spec.ts" region="import-ComponentFixtureAutoDetect" header="app/banner/banner.component.detect-changes.spec.ts (import)" ng-version="9.0.0-rc.11"><div style="display:none">import { <a href="api/core/testing/ComponentFixtureAutoDetect" class="code-anchor">ComponentFixtureAutoDetect</a> } from '@angular/core/testing';</div><header class="ng-star-inserted">app/banner/banner.component.detect-changes.spec.ts (import)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner.component.detect-changes.spec.ts (import)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/testing/ComponentFixtureAutoDetect" class="code-anchor"><span class="typ">ComponentFixtureAutoDetect</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core/testing'</span><span class="pun">;</span></code>
    </pre></aio-code></code-example><p translation-result="on">然后把它添加到测试模块配置的 <code>providers</code> 数组中：</p><p translation-origin="off">Then add it to the <code>providers</code> array of the testing module configuration:</p><code-example path="testing/src/app/banner/banner.component.detect-changes.spec.ts" region="auto-detect" header="app/banner/banner.component.detect-changes.spec.ts (AutoDetect)" ng-version="9.0.0-rc.11"><div style="display:none">TestBed.configureTestingModule({ declarations: [ BannerComponent ], providers: [ { provide: <a href="api/core/testing/ComponentFixtureAutoDetect" class="code-anchor">ComponentFixtureAutoDetect</a>, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: true } ] });</div><header class="ng-star-inserted">app/banner/banner.component.detect-changes.spec.ts (AutoDetect)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner.component.detect-changes.spec.ts (AutoDetect)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
  declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
  providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
    </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/core/testing/ComponentFixtureAutoDetect" class="code-anchor"><span class="typ">ComponentFixtureAutoDetect</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> </span><span class="kwd">true</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
  </span><span class="pun">]</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">这三个测试阐明了自动变更检测的工作原理。</p><p translation-origin="off">Here are three tests that illustrate how automatic change detection works.</p><code-example path="testing/src/app/banner/banner.component.detect-changes.spec.ts" region="auto-detect-tests" header="app/banner/banner.component.detect-changes.spec.ts (AutoDetect Tests)" ng-version="9.0.0-rc.11"><div style="display:none">it('should display original title', () =&gt; { // Hooray! No `fixture.detectChanges()` needed expect(h1.textContent).toContain(comp.title); }); it('should still see original title after comp.title change', () =&gt; { const oldTitle = comp.title; comp.title = 'Test <a href="api/platform-browser/Title" class="code-anchor">Title</a>'; // Displayed title is old because Angular didn't hear the change :( expect(h1.textContent).toContain(oldTitle); }); it('should display updated title after detectChanges', () =&gt; { comp.title = 'Test <a href="api/platform-browser/Title" class="code-anchor">Title</a>'; fixture.detectChanges(); // detect <a href="api/core/QueryList#changes" class="code-anchor">changes</a> explicitly expect(h1.textContent).toContain(comp.title); });</div><header class="ng-star-inserted">app/banner/banner.component.detect-changes.spec.ts (AutoDetect Tests)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner.component.detect-changes.spec.ts (AutoDetect Tests)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should display original title'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// Hooray! No `fixture.detectChanges()` needed</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">h1</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="pln">comp</span><span class="pun">.</span><span class="pln">title</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should still see original title after comp.title change'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> oldTitle </span><span class="pun">=</span><span class="pln"> comp</span><span class="pun">.</span><span class="pln">title</span><span class="pun">;</span><span class="pln">
  comp</span><span class="pun">.</span><span class="pln">title </span><span class="pun">=</span><span class="pln"> </span><span class="str">'Test </span><a href="api/platform-browser/Title" class="code-anchor"><span class="str">Title</span></a><span class="str">'</span><span class="pun">;</span><span class="pln">
  </span><span class="com">// Displayed title is old because Angular didn't hear the change :(</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">h1</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="pln">oldTitle</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should display updated title after detectChanges'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  comp</span><span class="pun">.</span><span class="pln">title </span><span class="pun">=</span><span class="pln"> </span><span class="str">'Test </span><a href="api/platform-browser/Title" class="code-anchor"><span class="str">Title</span></a><span class="str">'</span><span class="pun">;</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// detect </span><a href="api/core/QueryList#changes" class="code-anchor"><span class="com">changes</span></a><span class="com"> explicitly</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">h1</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="pln">comp</span><span class="pun">.</span><span class="pln">title</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">第一个测试程序展示了自动检测的好处。</p><p translation-origin="off">The first test shows the benefit of automatic change detection.</p><p translation-result="on">第二和第三个测试程序显示了它重要的局限性。 Angular 测试环境<strong>不会</strong>知道测试程序改变了组件的 <code>title</code> 属性。 自动检测只对异步行为比如承诺的解析、计时器和 DOM 事件作出反应。 但是直接修改组件属性值的这种同步更新是不会触发<strong>自动检测</strong>的。 测试程序必须手动调用 <code>fixture.detectChange()</code>，来触发新一轮的变更检测周期。</p><p translation-origin="off">The second and third test reveal an important limitation. The Angular testing environment does <em>not</em> know that the test changed the component's <code>title</code>. The <code><a href="api/core/testing/ComponentFixtureAutoDetect" class="code-anchor">ComponentFixtureAutoDetect</a></code> service responds to <em>asynchronous activities</em> such as promise resolution, timers, and DOM events. But a direct, synchronous update of the component property is invisible. The test must call <code>fixture.detectChanges()</code> manually to trigger another cycle of change detection.</p><div class="alert is-helpful"><p translation-result="on">相比于受测试工具有没有执行变更检测的困扰，本章中的例子更愿意<strong>总是显式</strong>调用 <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code>。 即使是在不需要的时候，频繁调用 <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code> 也没有任何坏处。</p><p translation-origin="off">Rather than wonder when the test fixture will or won't perform change detection, the samples in this guide <em>always call</em> <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code> <em>explicitly</em>. There is no harm in calling <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code> more often than is strictly necessary.</p></div><hr><a id="dispatch-event"></a><h4 id="change-an-input-value-with-dispatchevent" translation-result="on">使用 <code><a href="" class="code-anchor">dispatchEvent()</a></code> 修改输入值<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#change-an-input-value-with-dispatchevent"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="change-an-input-value-with-dispatchevent">Change an input value with <em>dispatchEvent()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#change-an-input-value-with-dispatchevent"><i class="material-icons">link</i></a></h4><p translation-result="on">要想模拟用户输入，你就要找到 <code>&lt;input&gt;</code> 元素并设置它的 <code>value</code> 属性。</p><p translation-origin="off">To simulate user input, you can find the input element and set its <code>value</code> property.</p><p translation-result="on">你要调用 <code>fixture.detectChanges()</code> 来触发 Angular 的变更检测。 但那只是一个基本的中间步骤。</p><p translation-origin="off">You will call <code>fixture.detectChanges()</code> to trigger Angular's change detection. But there is an essential, intermediate step.</p><p translation-result="on">Angular 不知道你设置了这个 <code>&lt;input&gt;</code> 元素的 <code>value</code> 属性。 在你通过调用 <code><a href="" class="code-anchor">dispatchEvent()</a></code> 触发了该输入框的 <code>input</code> 事件之前，它不能读到那个值。 <em>调用完之后</em>你再调用 <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code>。</p><p translation-origin="off">Angular doesn't know that you set the input element's <code>value</code> property. It won't read that property until you raise the element's <code>input</code> event by calling <code><a href="" class="code-anchor">dispatchEvent()</a></code>. <em>Then</em> you call <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code>.</p><p translation-result="on">下面的例子演示了这个调用顺序。</p><p translation-origin="off">The following example demonstrates the proper sequence.</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="title-case-pipe" header="app/hero/hero-detail.component.spec.ts (pipe test)" ng-version="9.0.0-rc.11"><div style="display:none">it('should convert hero name to <a href="api/platform-browser/Title" class="code-anchor">Title</a> Case', () =&gt; { // get the name's input and display elements from the DOM const hostElement = fixture.nativeElement; const nameInput: HTMLInputElement = hostElement.querySelector('input'); const nameDisplay: HTMLElement = hostElement.querySelector('span'); // simulate user entering a new name into the input box nameInput.value = 'quick BROWN fOx'; // dispatch a DOM event so that Angular learns of input value change. // use newEvent utility function (not provided by Angular) for better <a href="api/animations/browser" class="code-anchor">browser</a> compatibility nameInput.dispatchEvent(newEvent('input')); // Tell Angular to <a href="api/forms/NgModel#update" class="code-anchor">update</a> the display binding through the title pipe fixture.detectChanges(); expect(nameDisplay.textContent).toBe('Quick Brown Fox'); });</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (pipe test)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (pipe test)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should convert hero name to </span><a href="api/platform-browser/Title" class="code-anchor"><span class="str">Title</span></a><span class="str"> Case'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// get the name's input and display elements from the DOM</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> hostElement </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> nameInput</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLInputElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> hostElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'input'</span><span class="pun">);</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> nameDisplay</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> hostElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'span'</span><span class="pun">);</span><span class="pln">

  </span><span class="com">// simulate user entering a new name into the input box</span><span class="pln">
  nameInput</span><span class="pun">.</span><span class="kwd">value</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="str">'quick BROWN  fOx'</span><span class="pun">;</span><span class="pln">

  </span><span class="com">// dispatch a DOM event so that Angular learns of input value change.</span><span class="pln">
  </span><span class="com">// use newEvent utility function (not provided by Angular) for better </span><a href="api/animations/browser" class="code-anchor"><span class="com">browser</span></a><span class="com"> compatibility</span><span class="pln">
  nameInput</span><span class="pun">.</span><span class="pln">dispatchEvent</span><span class="pun">(</span><span class="pln">newEvent</span><span class="pun">(</span><span class="str">'input'</span><span class="pun">));</span><span class="pln">

  </span><span class="com">// Tell Angular to </span><a href="api/forms/NgModel#update" class="code-anchor"><span class="com">update</span></a><span class="com"> the display binding through the title pipe</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">nameDisplay</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'Quick Brown  Fox'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><hr><h3 id="component-with-external-files" translation-result="on">带有外部文件的组件<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-with-external-files"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="component-with-external-files">Component with external files<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-with-external-files"><i class="material-icons">link</i></a></h3><p translation-result="on">上面的 <code>BannerComponent</code> 定义了一个<em>内联模板</em>和<em>内联 CSS</em>，分别是在 <code>@<a href="api/core/Component#template" class="code-anchor">Component.template</a></code> 和 <code>@<a href="api/core/Component#styles" class="code-anchor">Component.styles</a></code> 属性中指定的。</p><p translation-origin="off">The <code>BannerComponent</code> above is defined with an <em>inline template</em> and <em>inline css</em>, specified in the <code>@<a href="api/core/Component#template" class="code-anchor">Component.template</a></code> and <code>@<a href="api/core/Component#styles" class="code-anchor">Component.styles</a></code> properties respectively.</p><p translation-result="on">很多组件会分别用 <code>@<a href="api/core/Component#templateUrl" class="code-anchor">Component.templateUrl</a></code> 和 <code>@<a href="api/core/Component#styleUrls" class="code-anchor">Component.styleUrls</a></code> 属性来指定<em>外部模板</em>和<em>外部 CSS</em>，就像下面这个 <code>BannerComponent</code> 的变体中所做的一样：</p><p translation-origin="off">Many components specify <em>external templates</em> and <em>external css</em> with the <code>@<a href="api/core/Component#templateUrl" class="code-anchor">Component.templateUrl</a></code> and <code>@<a href="api/core/Component#styleUrls" class="code-anchor">Component.styleUrls</a></code> properties respectively, as the following variant of <code>BannerComponent</code> does.</p><code-example path="testing/src/app/banner/banner-external.component.ts" region="metadata" header="app/banner/banner-external.component.ts (metadata)" ng-version="9.0.0-rc.11"><div style="display:none">@<a href="api/core/Component" class="code-anchor">Component</a>({ selector: 'app-banner', <a href="api/core/Component#templateUrl" class="code-anchor">templateUrl</a>: './banner-external.component.html', <a href="api/core/Component#styleUrls" class="code-anchor">styleUrls</a>: ['./banner-external.component.css'] })</div><header class="ng-star-inserted">app/banner/banner-external.component.ts (metadata)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner-external.component.ts (metadata)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">
  selector</span><span class="pun">:</span><span class="pln"> </span><span class="str">'app-banner'</span><span class="pun">,</span><span class="pln">
  </span><a href="api/core/Component#templateUrl" class="code-anchor"><span class="pln">templateUrl</span></a><span class="pun">:</span><span class="pln"> </span><span class="str">'./banner-external.component.html'</span><span class="pun">,</span><span class="pln">
  </span><a href="api/core/Component#styleUrls" class="code-anchor"><span class="pln">styleUrls</span></a><span class="pun">:</span><span class="pln">  </span><span class="pun">[</span><span class="str">'./banner-external.component.css'</span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span></code>
    </pre></aio-code></code-example><p translation-result="on">这个语法告诉 Angular 编译器在编译期间读取外部文件。</p><p translation-origin="off">This syntax tells the Angular compiler to read the external files during component compilation.</p><p translation-result="on">当你运行 CLI 的 <code>ng test</code> 命令的时候这毫无问题，因为它会<em>在运行测试之前先编译该应用</em>。</p><p translation-origin="off">That's not a problem when you run the CLI <code>ng test</code> command because it <em>compiles the app before running the tests</em>.</p><p translation-result="on">不过，如果你在<strong>非 CLI 环境下</strong>运行这些测试，那么对该组件的测试就可能失败。 比如，如果你在像 <a href="http://plnkr.co/">plunker</a> 这样的 Web 编程环境下运行 <code>BannerComponent</code> 的测试，就会看到如下信息：</p><p translation-origin="off">However, if you run the tests in a <strong>non-CLI environment</strong>, tests of this component may fail. For example, if you run the <code>BannerComponent</code> tests in a web coding environment such as <a href="https://plnkr.co/">plunker</a>, you'll see a message like this one:</p><code-example language="sh" class="code-shell" hidecopy="" ng-version="9.0.0-rc.11"><div style="display:none">Error: This test module uses the component BannerComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test.</div><aio-code><pre class="lang-sh prettyprint">      
      <code class="animated fadeIn"><span class="typ">Error</span><span class="pun">:</span><span class="pln"> </span><span class="typ">This</span><span class="pln"> test module uses the component </span><span class="typ">BannerComponent</span><span class="pln">
which is using a </span><span class="str">"templateUrl"</span><span class="pln"> or </span><span class="str">"styleUrls"</span><span class="pun">,</span><span class="pln"> but they were never compiled</span><span class="pun">.</span><span class="pln">
</span><span class="typ">Please</span><span class="pln"> call </span><span class="str">"TestBed.compileComponents"</span><span class="pln"> before your test</span><span class="pun">.</span></code>
    </pre></aio-code></code-example><p translation-result="on">如果在<em>测试自身期间</em>，运行环境试图编译源码，就会出现这个测试错误信息。</p><p translation-origin="off">You get this test failure message when the runtime environment compiles the source code <em>during the tests themselves</em>.</p><p translation-result="on">要解决这个问题，可以像<a href="guide/testing#compile-components">稍后</a>解释的那样调用一次 <code>compileComponents()</code>。</p><p translation-origin="off">To correct the problem, call <code>compileComponents()</code> as explained <a href="guide/testing#compile-components">below</a>.</p><a id="component-with-dependency"></a><h3 id="component-with-a-dependency" translation-result="on">带依赖的组件<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-with-a-dependency"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="component-with-a-dependency">Component with a dependency<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-with-a-dependency"><i class="material-icons">link</i></a></h3><p translation-result="on">组件经常依赖其他服务。</p><p translation-origin="off">Components often have service dependencies.</p><p translation-result="on"><code>WelcomeComponent</code> 为登陆的用户显示一条欢迎信息。它从注入的 <code>UserService</code> 的属性得知用户的身份：</p><p translation-origin="off">The <code>WelcomeComponent</code> displays a welcome message to the logged in user. It knows who the user is based on a property of the injected <code>UserService</code>:</p><code-example path="testing/src/app/welcome/welcome.component.ts" header="app/welcome/welcome.component.ts" ng-version="9.0.0-rc.11"><div style="display:none">import { <a href="api/core/Component" class="code-anchor">Component</a>, <a href="api/core/OnInit" class="code-anchor">OnInit</a> } from '@angular/core'; import { UserService } from '../<a href="api/forms/NgModel#model" class="code-anchor">model</a>/user.service'; @<a href="api/core/Component" class="code-anchor">Component</a>({ selector: 'app-welcome', template: '&lt;h3 class="welcome"&gt;&lt;i&gt;{{welcome}}&lt;/i&gt;&lt;/h3&gt;' }) export class WelcomeComponent implements <a href="api/core/OnInit" class="code-anchor">OnInit</a> { welcome: string; constructor(private userService: UserService) { } ngOnInit(): void { this.welcome = this.userService.isLoggedIn ? 'Welcome, ' + this.userService.user.name : 'Please <a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor">log</a> in.'; } }</div><header class="ng-star-inserted">app/welcome/welcome.component.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/welcome/welcome.component.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/Component" class="code-anchor"><span class="typ">Component</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/OnInit" class="code-anchor"><span class="typ">OnInit</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core'</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">UserService</span><span class="pln"> </span><span class="pun">}</span><span class="pln">       </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'../</span><a href="api/forms/NgModel#model" class="code-anchor"><span class="str">model</span></a><span class="str">/user.service'</span><span class="pun">;</span><span class="pln">

</span><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">
  selector</span><span class="pun">:</span><span class="pln"> </span><span class="str">'app-welcome'</span><span class="pun">,</span><span class="pln">
  </span><span class="kwd">template</span><span class="pun">:</span><span class="pln"> </span><span class="str">'&lt;h3 class="welcome"&gt;&lt;i&gt;{{welcome}}&lt;/i&gt;&lt;/h3&gt;'</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WelcomeComponent</span><span class="pln">  </span><span class="kwd">implements</span><span class="pln"> </span><a href="api/core/OnInit" class="code-anchor"><span class="typ">OnInit</span></a><span class="pln"> </span><span class="pun">{</span><span class="pln">
  welcome</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="kwd">private</span><span class="pln"> userService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">UserService</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">}</span><span class="pln">

  ngOnInit</span><span class="pun">():</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">welcome </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">userService</span><span class="pun">.</span><span class="pln">isLoggedIn </span><span class="pun">?</span><span class="pln">
      </span><span class="str">'Welcome, '</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">userService</span><span class="pun">.</span><span class="pln">user</span><span class="pun">.</span><span class="pln">name </span><span class="pun">:</span><span class="pln"> </span><span class="str">'Please </span><a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor"><span class="str">log</span></a><span class="str"> in.'</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>WelcomeComponent</code> 带有与服务交互的决策逻辑，这些逻辑让该组件值得测试。 下面是 <code>app/welcome/welcome.component.spec.ts</code> 中的测试模块配置：</p><p translation-origin="off">The <code>WelcomeComponent</code> has decision logic that interacts with the service, logic that makes this component worth testing. Here's the testing module configuration for the spec file, <code>app/welcome/welcome.component.spec.ts</code>:</p><code-example path="testing/src/app/welcome/welcome.component.spec.ts" region="config-test-module" header="app/welcome/welcome.component.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">TestBed.configureTestingModule({ declarations: [ WelcomeComponent ], // providers: [ UserService ] // NO! Don't provide the real service! // Provide a test-double instead providers: [ {provide: UserService, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: userServiceStub } ] });</div><header class="ng-star-inserted">app/welcome/welcome.component.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/welcome/welcome.component.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
   declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">WelcomeComponent</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
</span><span class="com">// providers:    [ UserService ]  // NO! Don't provide the real service!</span><span class="pln">
                                  </span><span class="com">// Provide a test-double instead</span><span class="pln">
   providers</span><span class="pun">:</span><span class="pln">    </span><span class="pun">[</span><span class="pln"> </span><span class="pun">{</span><span class="pln">provide</span><span class="pun">:</span><span class="pln"> </span><span class="typ">UserService</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> userServiceStub </span><span class="pun">}</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">这次，在测试配置里不但声明了被测试的组件，而且在 <code>providers</code> 数组中添加了 <code>UserService</code> 依赖。但不是真实的 <code>UserService</code>。</p><p translation-origin="off">This time, in addition to declaring the <em>component-under-test</em>, the configuration adds a <code>UserService</code> provider to the <code>providers</code> list. But not the real <code>UserService</code>.</p><a id="service-test-doubles"></a><h4 id="provide-service-test-doubles" translation-result="on">提供服务的测试替身<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#provide-service-test-doubles"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="provide-service-test-doubles">Provide service test doubles<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#provide-service-test-doubles"><i class="material-icons">link</i></a></h4><p translation-result="on">被测试的组件不一定要注入真正的服务。实际上，服务的替身（Stub - 桩, Fake - 假冒品, Spy - 间谍或者 Mock - 模拟对象）通常会更加合适。 spec 的主要目的是测试组件，而不是服务。真实的服务可能连自身都有问题，不应该让它干扰对组件的测试。</p><p translation-origin="off">A <em>component-under-test</em> doesn't have to be injected with real services. In fact, it is usually better if they are test doubles (stubs, fakes, spies, or mocks). The purpose of the spec is to test the component, not the service, and real services can be trouble.</p><p translation-result="on">注入真实的 <code>UserService</code> 有可能很麻烦。真实的服务可能询问用户登录凭据，也可能试图连接认证服务器。 可能很难处理这些行为。所以在真实的 <code>UserService</code> 的位置创建和注册 <code>UserService</code> 替身，会让测试更加容易和安全。</p><p translation-origin="off">Injecting the real <code>UserService</code> could be a nightmare. The real service might ask the user for login credentials and attempt to reach an authentication server. These behaviors can be hard to intercept. It is far easier and safer to create and register a test double in place of the real <code>UserService</code>.</p><p translation-result="on">这个测试套件提供了 <code>UserService</code> 的一个最小化模拟对象，它能满足 <code>WelcomeComponent</code> 及其测试的需求：</p><p translation-origin="off">This particular test suite supplies a minimal mock of the <code>UserService</code> that satisfies the needs of the <code>WelcomeComponent</code> and its tests:</p><code-example path="testing/src/app/welcome/welcome.component.spec.ts" region="user-service-stub" header="app/welcome/welcome.component.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">let userServiceStub: Partial&lt;UserService&gt;; userServiceStub = { isLoggedIn: true, user: { name: 'Test <a href="api/common/http/HttpEventType#User" class="code-anchor">User</a>'} };</div><header class="ng-star-inserted">app/welcome/welcome.component.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/welcome/welcome.component.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">let</span><span class="pln"> userServiceStub</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Partial</span><span class="pun">&lt;</span><span class="typ">UserService</span><span class="pun">&gt;;</span><span class="pln">

userServiceStub </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  isLoggedIn</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">,</span><span class="pln">
  user</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> name</span><span class="pun">:</span><span class="pln"> </span><span class="str">'Test </span><a href="api/common/http/HttpEventType#User" class="code-anchor"><span class="str">User</span></a><span class="str">'</span><span class="pun">}</span><span class="pln">
</span><span class="pun">};</span></code>
    </pre></aio-code></code-example><a id="get-injected-service"></a><h4 id="get-injected-services" translation-result="on">获取注入的服务<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#get-injected-services"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="get-injected-services">Get injected services<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#get-injected-services"><i class="material-icons">link</i></a></h4><p translation-result="on">测试程序需要访问被注入到 <code>WelcomeComponent</code> 中的 <code>UserService</code>（stub 类）。</p><p translation-origin="off">The tests need access to the (stub) <code>UserService</code> injected into the <code>WelcomeComponent</code>.</p><p translation-result="on">Angular 的注入系统是层次化的。 可以有很多层注入器，从根 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 创建的注入器下来贯穿整个组件树。</p><p translation-origin="off">Angular has a hierarchical injection system. There can be injectors at multiple levels, from the root injector created by the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> down through the component tree.</p><p translation-result="on">最安全并<strong>总是有效</strong>的获取注入服务的方法，是<strong>从被测组件的注入器获取</strong>。 组件注入器是 fixture 的 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 的属性之一。</p><p translation-origin="off">The safest way to get the injected service, the way that <strong><em>always works</em></strong>, is to <strong>get it from the injector of the <em>component-under-test</em></strong>. The component injector is a property of the fixture's <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code>.</p><code-example path="testing/src/app/welcome/welcome.component.spec.ts" region="injected-service" header="WelcomeComponent's injector" ng-version="9.0.0-rc.11"><div style="display:none">// UserService actually injected into the component userService = fixture.debugElement.injector.get(UserService);</div><header class="ng-star-inserted">WelcomeComponent's injector</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from WelcomeComponent's injector">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// UserService actually injected into the component</span><span class="pln">
userService </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">.</span><span class="pln">injector</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><span class="typ">UserService</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><a id="testbed-inject"></a><h4 id="testbedinject"><em>TestBed.inject()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testbedinject"><i class="material-icons">link</i></a></h4><p translation-result="on">你也可能通过 <code>TestBed.inject()</code> 来使用根注入器获取该服务。 这样更容易记住而且不那么啰嗦。 不过这只有当 Angular 组件需要的恰好是该测试的根注入器时才能正常工作。</p><p translation-origin="off">You <em>may</em> also be able to get the service from the root injector via <code>TestBed.inject()</code>. This is easier to remember and less verbose. But it only works when Angular injects the component with the service instance in the test's root injector.</p><p translation-result="on">在这个测试套件中，<code>UserService</code> <em>唯一</em>的提供商就是根测试模块中的，因此调用 <code>TestBed.inject()</code> 就是安全的，代码如下：</p><p translation-origin="off">In this test suite, the <em>only</em> provider of <code>UserService</code> is the root testing module, so it is safe to call <code>TestBed.inject()</code> as follows:</p><code-example path="testing/src/app/welcome/welcome.component.spec.ts" region="inject-from-testbed" header="TestBed injector" ng-version="9.0.0-rc.11"><div style="display:none">// UserService from the root injector userService = TestBed.inject(UserService);</div><header class="ng-star-inserted">TestBed injector</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from TestBed injector">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// UserService from the root injector</span><span class="pln">
userService </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">inject</span><span class="pun">(</span><span class="typ">UserService</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><div class="alert is-helpful"><p translation-result="on">对于那些不能用 <code>TestBed.inject()</code> 的测试用例，请参见<a href="guide/testing#component-override">改写组件的提供商</a>一节，那里解释了何时以及为何必须改从组件自身的注入器中获取服务。</p><p translation-origin="off">For a use case in which <code>TestBed.inject()</code> does not work, see the <a href="guide/testing#component-override"><em>Override component providers</em></a> section that explains when and why you must get the service from the component's injector instead.</p></div><a id="service-from-injector"></a><h4 id="always-get-the-service-from-an-injector" translation-result="on">总是从注入其中获取服务<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#always-get-the-service-from-an-injector"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="always-get-the-service-from-an-injector">Always get the service from an injector<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#always-get-the-service-from-an-injector"><i class="material-icons">link</i></a></h4><p translation-result="on">请不要引用测试代码里提供给测试模块的 <code>userServiceStub</code> 对象。<strong>这样不行！</strong> 被注入组件的 <code>userService</code> 实例是完全<strong>不一样</strong>的对象，它提供的是 <code>userServiceStub</code> 的克隆。</p><p translation-origin="off">Do <em>not</em> reference the <code>userServiceStub</code> object that's provided to the testing module in the body of your test. <strong>It does not work!</strong> The <code>userService</code> instance injected into the component is a completely <em>different</em> object, a clone of the provided <code>userServiceStub</code>.</p><code-example path="testing/src/app/welcome/welcome.component.spec.ts" region="stub-not-injected" header="app/welcome/welcome.component.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">it('stub object and injected UserService should not be the same', () =&gt; { expect(userServiceStub === userService).toBe(false); // Changing the stub object has no effect on the injected service userServiceStub.isLoggedIn = false; expect(userService.isLoggedIn).toBe(true); });</div><header class="ng-star-inserted">app/welcome/welcome.component.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/welcome/welcome.component.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'stub object and injected UserService should not be the same'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">userServiceStub </span><span class="pun">===</span><span class="pln"> userService</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">false</span><span class="pun">);</span><span class="pln">

  </span><span class="com">// Changing the stub object has no effect on the injected service</span><span class="pln">
  userServiceStub</span><span class="pun">.</span><span class="pln">isLoggedIn </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">false</span><span class="pun">;</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">userService</span><span class="pun">.</span><span class="pln">isLoggedIn</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><a id="welcome-spec-setup"></a><h4 id="final-setup-and-tests" translation-result="on">最终的准备及测试代码<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#final-setup-and-tests"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="final-setup-and-tests">Final setup and tests<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#final-setup-and-tests"><i class="material-icons">link</i></a></h4><p translation-result="on">下面是使用 <code>TestBed.inject()</code> 的完整的 <code>beforeEach()</code>：</p><p translation-origin="off">Here's the complete <code>beforeEach()</code>, using <code>TestBed.inject()</code>:</p><code-example path="testing/src/app/welcome/welcome.component.spec.ts" region="setup" header="app/welcome/welcome.component.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">let userServiceStub: Partial&lt;UserService&gt;; beforeEach(() =&gt; { // stub UserService for test purposes userServiceStub = { isLoggedIn: true, user: { name: 'Test <a href="api/common/http/HttpEventType#User" class="code-anchor">User</a>'} }; TestBed.configureTestingModule({ declarations: [ WelcomeComponent ], providers: [ {provide: UserService, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: userServiceStub } ] }); fixture = TestBed.createComponent(WelcomeComponent); comp = fixture.componentInstance; // UserService from the root injector userService = TestBed.inject(UserService); // get the "welcome" element by CSS selector (e.g., by class name) el = fixture.nativeElement.querySelector('.welcome'); });</div><header class="ng-star-inserted">app/welcome/welcome.component.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/welcome/welcome.component.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">let</span><span class="pln"> userServiceStub</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Partial</span><span class="pun">&lt;</span><span class="typ">UserService</span><span class="pun">&gt;;</span><span class="pln">

beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// stub UserService for test purposes</span><span class="pln">
  userServiceStub </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    isLoggedIn</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">,</span><span class="pln">
    user</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> name</span><span class="pun">:</span><span class="pln"> </span><span class="str">'Test </span><a href="api/common/http/HttpEventType#User" class="code-anchor"><span class="str">User</span></a><span class="str">'</span><span class="pun">}</span><span class="pln">
  </span><span class="pun">};</span><span class="pln">

  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
     declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">WelcomeComponent</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
     providers</span><span class="pun">:</span><span class="pln">    </span><span class="pun">[</span><span class="pln"> </span><span class="pun">{</span><span class="pln">provide</span><span class="pun">:</span><span class="pln"> </span><span class="typ">UserService</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> userServiceStub </span><span class="pun">}</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">WelcomeComponent</span><span class="pun">);</span><span class="pln">
  comp    </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">

  </span><span class="com">// UserService from the root injector</span><span class="pln">
  userService </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">inject</span><span class="pun">(</span><span class="typ">UserService</span><span class="pun">);</span><span class="pln">

  </span><span class="com">//  get the "welcome" element by CSS selector (e.g., by class name)</span><span class="pln">
  el </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'.welcome'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">下面是一些测试程序:</p><p translation-origin="off">And here are some tests:</p><code-example path="testing/src/app/welcome/welcome.component.spec.ts" region="tests" header="app/welcome/welcome.component.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">it('should welcome the user', () =&gt; { fixture.detectChanges(); const content = el.textContent; expect(content).toContain('Welcome', '"Welcome ..."'); expect(content).toContain('Test <a href="api/common/http/HttpEventType#User" class="code-anchor">User</a>', 'expected name'); }); it('should welcome "Bubba"', () =&gt; { userService.user.name = 'Bubba'; // welcome <a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a> hasn't been shown yet fixture.detectChanges(); expect(el.textContent).toContain('Bubba'); }); it('should request login if not logged in', () =&gt; { userService.isLoggedIn = false; // welcome <a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a> hasn't been shown yet fixture.detectChanges(); const content = el.textContent; expect(content).not.toContain('Welcome', 'not welcomed'); expect(content).toMatch(/<a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor">log</a> in/i, '"<a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor">log</a> in"'); });</div><header class="ng-star-inserted">app/welcome/welcome.component.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/welcome/welcome.component.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should welcome the user'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> content </span><span class="pun">=</span><span class="pln"> el</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">;</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">content</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="str">'Welcome'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'"Welcome ..."'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">content</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="str">'Test </span><a href="api/common/http/HttpEventType#User" class="code-anchor"><span class="str">User</span></a><span class="str">'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'expected name'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should welcome "Bubba"'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  userService</span><span class="pun">.</span><span class="pln">user</span><span class="pun">.</span><span class="pln">name </span><span class="pun">=</span><span class="pln"> </span><span class="str">'Bubba'</span><span class="pun">;</span><span class="pln"> </span><span class="com">// welcome </span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="com">message</span></a><span class="com"> hasn't been shown yet</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">el</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="str">'Bubba'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should request login if not logged in'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  userService</span><span class="pun">.</span><span class="pln">isLoggedIn </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">false</span><span class="pun">;</span><span class="pln"> </span><span class="com">// welcome </span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="com">message</span></a><span class="com"> hasn't been shown yet</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> content </span><span class="pun">=</span><span class="pln"> el</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">;</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">content</span><span class="pun">).</span><span class="kwd">not</span><span class="pun">.</span><span class="pln">toContain</span><span class="pun">(</span><span class="str">'Welcome'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'not welcomed'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">content</span><span class="pun">).</span><span class="pln">toMatch</span><span class="pun">(</span><span class="str">/</span><a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor"><span class="str">log</span></a><span class="str"> in/</span><span class="pln">i</span><span class="pun">,</span><span class="pln"> </span><span class="str">'"</span><a href="api/animations/browser/testing/MockAnimationDriver#log" class="code-anchor"><span class="str">log</span></a><span class="str"> in"'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">第一个测试程序是合法测试程序，它确认这个被模拟的 <code>UserService</code> 是否被调用和工作正常。</p><p translation-origin="off">The first is a sanity test; it confirms that the stubbed <code>UserService</code> is called and working.</p><div class="alert is-helpful"><p translation-result="on">Jasmine 匹配器的第二个参数（比如 <code>'expected name'</code>）是一个可选的失败标签。 如果这个期待语句失败了，Jasmine 就会把这个标签追加显示到这条个期待语句的失败信息后面。 对于具有多个期待语句的规约，它可以帮助澄清到底什么出错了，以及哪个期待语句失败了。</p><p translation-origin="off">The second parameter to the Jasmine matcher (e.g., <code>'expected name'</code>) is an optional failure label. If the expectation fails, Jasmine appends this label to the expectation failure message. In a spec with multiple expectations, it can help clarify what went wrong and which expectation failed.</p></div><p translation-result="on">接下来的测试程序确认当服务返回不同的值时组件的逻辑是否工作正常。 第二个测试程序验证变换用户名字的效果。 第三个测试程序检查如果用户没有登录，组件是否显示正确消息。</p><p translation-origin="off">The remaining tests confirm the logic of the component when the service returns different values. The second test validates the effect of changing the user name. The third test checks that the component displays the proper message when there is no logged-in user.</p><hr><a id="component-with-async-service"></a><h3 id="component-with-async-service" translation-result="on">带有异步服务的组件<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-with-async-service"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="component-with-async-service">Component with async service<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-with-async-service"><i class="material-icons">link</i></a></h3><p translation-result="on">在这个例子中，<code>AboutComponent</code> 的模板中还有一个 <code>TwainComponent</code>。 <code>TwainComponent</code> 用于显示引自马克·吐温的话。</p><p translation-origin="off">In this sample, the <code>AboutComponent</code> template hosts a <code>TwainComponent</code>. The <code>TwainComponent</code> displays Mark Twain quotes.</p><code-example path="testing/src/app/twain/twain.component.ts" region="template" header="app/twain/twain.component.ts (template)" ng-version="9.0.0-rc.11"><div style="display:none">template: ` &lt;p class="twain"&gt;&lt;i&gt;{{quote | async}}&lt;/i&gt;&lt;/p&gt; &lt;button (click)="getQuote()"&gt;Next quote&lt;/button&gt; &lt;p class="error" *<a href="api/common/NgIf" class="code-anchor">ngIf</a>="errorMessage"&gt;{{ errorMessage }}&lt;/p&gt;`,</div><header class="ng-star-inserted">app/twain/twain.component.ts (template)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/twain/twain.component.ts (template)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">template</span><span class="pun">:</span><span class="pln"> </span><span class="str">`
  &lt;p class="twain"&gt;&lt;i&gt;{{quote | async}}&lt;/i&gt;&lt;/p&gt;
  &lt;button (click)="getQuote()"&gt;Next quote&lt;/button&gt;
  &lt;p class="error" *</span><a href="api/common/NgIf" class="code-anchor"><span class="str">ngIf</span></a><span class="str">="errorMessage"&gt;{{ errorMessage }}&lt;/p&gt;`</span><span class="pun">,</span></code>
    </pre></aio-code></code-example><p translation-result="on">注意该组件的 <code>quote</code> 属性的值是通过 <code><a href="api/common/AsyncPipe" class="code-anchor">AsyncPipe</a></code> 传进来的。 这意味着该属性或者返回 <code>Promise</code> 或者返回 <code>Observable</code>。</p><p translation-origin="off">Note that the value of the component's <code>quote</code> property passes through an <code><a href="api/common/AsyncPipe" class="code-anchor">AsyncPipe</a></code>. That means the property returns either a <code>Promise</code> or an <code>Observable</code>.</p><p translation-result="on">在这个例子中，<code>TwainComponent.getQuote()</code> 方法告诉你 <code>quote</code> 方法返回的是 <code>Observable</code>。</p><p translation-origin="off">In this example, the <code>TwainComponent.getQuote()</code> method tells you that the <code>quote</code> property returns an <code>Observable</code>.</p><code-example path="testing/src/app/twain/twain.component.ts" region="get-quote" header="app/twain/twain.component.ts (getQuote)" ng-version="9.0.0-rc.11"><div style="display:none">getQuote() { this.errorMessage = ''; this.quote = this.twainService.getQuote().pipe( startWith('...'), catchError( (err: any) =&gt; { // Wait a turn because errorMessage already set once this turn setTimeout(() =&gt; this.errorMessage = err.message || err.toString()); return of('...'); // reset <a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a> to placeholder }) );</div><header class="ng-star-inserted">app/twain/twain.component.ts (getQuote)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/twain/twain.component.ts (getQuote)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">getQuote</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">errorMessage </span><span class="pun">=</span><span class="pln"> </span><span class="str">''</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">quote </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">twainService</span><span class="pun">.</span><span class="pln">getQuote</span><span class="pun">().</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln">
    startWith</span><span class="pun">(</span><span class="str">'...'</span><span class="pun">),</span><span class="pln">
    catchError</span><span class="pun">(</span><span class="pln"> </span><span class="pun">(</span><span class="pln">err</span><span class="pun">:</span><span class="pln"> any</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
      </span><span class="com">// Wait a turn because errorMessage already set once this turn</span><span class="pln">
      setTimeout</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">errorMessage </span><span class="pun">=</span><span class="pln"> err</span><span class="pun">.</span><span class="pln">message </span><span class="pun">||</span><span class="pln"> err</span><span class="pun">.</span><span class="pln">toString</span><span class="pun">());</span><span class="pln">
      </span><span class="kwd">return</span><span class="pln"> of</span><span class="pun">(</span><span class="str">'...'</span><span class="pun">);</span><span class="pln"> </span><span class="com">// reset </span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="com">message</span></a><span class="com"> to placeholder</span><span class="pln">
    </span><span class="pun">})</span><span class="pln">
  </span><span class="pun">);</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>TwainComponent</code> 会从一个注入进来的 <code>TwainService</code> 来获取这些引文。 在服务返回第一条引文之前，该组件会先返回一个占位值（<code>'...'</code>）的 <code>Observable</code>。</p><p translation-origin="off">The <code>TwainComponent</code> gets quotes from an injected <code>TwainService</code>. The component starts the returned <code>Observable</code> with a placeholder value (<code>'...'</code>), before the service can return its first quote.</p><p translation-result="on"><code>catchError</code> 会拦截服务中的错误，准备错误信息，并在成功分支中返回占位值。 它必须等一拍（tick）才能设置 <code>errorMessage</code>，以免在同一个变更检测周期中两次修改这个消息而导致报错。</p><p translation-origin="off">The <code>catchError</code> intercepts service errors, prepares an error message, and returns the placeholder value on the success channel. It must wait a tick to set the <code>errorMessage</code> in order to avoid updating that message twice in the same change detection cycle.</p><p translation-result="on">这就是你要测试的全部特性。</p><p translation-origin="off">These are all features you'll want to test.</p><h4 id="testing-with-a-spy" translation-result="on">使用间谍（Spy）进行测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-with-a-spy"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="testing-with-a-spy">Testing with a spy<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-with-a-spy"><i class="material-icons">link</i></a></h4><p translation-result="on">当测试组件时，只应该关心服务的公共 API。 通常来说，测试不应该自己向远端服务器发起调用。 它们应该对这些调用进行仿真。<code>app/twain/twain.component.spec.ts</code> 中的准备代码展示了实现方式之一：</p><p translation-origin="off">When testing a component, only the service's public API should matter. In general, tests themselves should not make calls to remote servers. They should emulate such calls. The setup in this <code>app/twain/twain.component.spec.ts</code> shows one way to do that:</p><code-example path="testing/src/app/twain/twain.component.spec.ts" region="setup" header="app/twain/twain.component.spec.ts (setup)" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(() =&gt; { testQuote = 'Test Quote'; // Create a fake TwainService object with a `getQuote()` spy const twainService = jasmine.createSpyObj('TwainService', ['getQuote']); // Make the spy return a synchronous Observable with the test data getQuoteSpy = twainService.getQuote.and.returnValue( of(testQuote) ); TestBed.configureTestingModule({ declarations: [ TwainComponent ], providers: [ { provide: TwainService, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: twainService } ] }); fixture = TestBed.createComponent(TwainComponent); component = fixture.componentInstance; quoteEl = fixture.nativeElement.querySelector('.twain'); });</div><header class="ng-star-inserted">app/twain/twain.component.spec.ts (setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/twain/twain.component.spec.ts (setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  testQuote </span><span class="pun">=</span><span class="pln"> </span><span class="str">'Test Quote'</span><span class="pun">;</span><span class="pln">

  </span><span class="com">// Create a fake TwainService object with a `getQuote()` spy</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> twainService </span><span class="pun">=</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="pln">createSpyObj</span><span class="pun">(</span><span class="str">'TwainService'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">[</span><span class="str">'getQuote'</span><span class="pun">]);</span><span class="pln">
  </span><span class="com">// Make the spy return a synchronous Observable with the test data</span><span class="pln">
  getQuoteSpy </span><span class="pun">=</span><span class="pln"> twainService</span><span class="pun">.</span><span class="pln">getQuote</span><span class="pun">.</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">returnValue</span><span class="pun">(</span><span class="pln"> of</span><span class="pun">(</span><span class="pln">testQuote</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln">

  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">TwainComponent</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
    providers</span><span class="pun">:</span><span class="pln">    </span><span class="pun">[</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><span class="typ">TwainService</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> twainService </span><span class="pun">}</span><span class="pln">
    </span><span class="pun">]</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">TwainComponent</span><span class="pun">);</span><span class="pln">
  component </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">
  quoteEl </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'.twain'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><a id="service-spy"></a><p translation-result="on">重点看这个间谍对象（spy）。</p><p translation-origin="off">Focus on the spy.</p><code-example path="testing/src/app/twain/twain.component.spec.ts" region="spy" ng-version="9.0.0-rc.11"><div style="display:none">// Create a fake TwainService object with a `getQuote()` spy const twainService = jasmine.createSpyObj('TwainService', ['getQuote']); // Make the spy return a synchronous Observable with the test data getQuoteSpy = twainService.getQuote.and.returnValue( of(testQuote) );</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// Create a fake TwainService object with a `getQuote()` spy</span><span class="pln">
</span><span class="kwd">const</span><span class="pln"> twainService </span><span class="pun">=</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="pln">createSpyObj</span><span class="pun">(</span><span class="str">'TwainService'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">[</span><span class="str">'getQuote'</span><span class="pun">]);</span><span class="pln">
</span><span class="com">// Make the spy return a synchronous Observable with the test data</span><span class="pln">
getQuoteSpy </span><span class="pun">=</span><span class="pln"> twainService</span><span class="pun">.</span><span class="pln">getQuote</span><span class="pun">.</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">returnValue</span><span class="pun">(</span><span class="pln"> of</span><span class="pun">(</span><span class="pln">testQuote</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span></code>
    </pre></aio-code></code-example><p translation-result="on">这个间谍的设计是：任何对 <code>getQuote</code> 的调用都会收到一个包含测试引文的可观察对象。 和真正的 <code>getQuote()</code> 方法不同，这个间谍跳过了服务器，直接返回了一个能立即解析出值的同步型可观察对象。</p><p translation-origin="off">The spy is designed such that any call to <code>getQuote</code> receives an observable with a test quote. Unlike the real <code>getQuote()</code> method, this spy bypasses the server and returns a synchronous observable whose value is available immediately.</p><p translation-result="on">虽然它的 <code>Observable</code> 是同步的，不过你仍然可以使用这个间谍对象写出很多有用的测试。</p><p translation-origin="off">You can write many useful tests with this spy, even though its <code>Observable</code> is synchronous.</p><a id="sync-tests"></a><h4 id="synchronous-tests" translation-result="on">同步测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#synchronous-tests"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="synchronous-tests">Synchronous tests<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#synchronous-tests"><i class="material-icons">link</i></a></h4><p translation-result="on">同步 <code>Observable</code> 的一大优点就是你可以把那些异步的流程转换成同步测试。</p><p translation-origin="off">A key advantage of a synchronous <code>Observable</code> is that you can often turn asynchronous processes into synchronous tests.</p><code-example path="testing/src/app/twain/twain.component.spec.ts" region="sync-test" ng-version="9.0.0-rc.11"><div style="display:none">it('should show quote after component initialized', () =&gt; { fixture.detectChanges(); // <a href="" class="code-anchor">onInit</a>() // sync spy result shows testQuote immediately after init expect(quoteEl.textContent).toBe(testQuote); expect(getQuoteSpy.calls.any()).toBe(true, 'getQuote called'); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should show quote after component initialized'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="" class="code-anchor"><span class="com">onInit</span></a><span class="com">()</span><span class="pln">

  </span><span class="com">// sync spy result shows testQuote immediately after init</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">testQuote</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">getQuoteSpy</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">any</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">,</span><span class="pln"> </span><span class="str">'getQuote called'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">因为间谍对象的结果是同步返回的，所以 <code>getQuote()</code> 方法会在 Angular 调用 <code>ngOnInit</code> 时触发的首次变更检测周期后立即修改屏幕上的消息。</p><p translation-origin="off">Because the spy result returns synchronously, the <code>getQuote()</code> method updates the message on screen immediately <em>after</em> the first change detection cycle during which Angular calls <code>ngOnInit</code>.</p><p translation-result="on">但测试出错路径的时候就没这么幸运了。 虽然该服务的间谍也会返回一个同步的错误对象，但是组件的那个方法中调用了 <code>setTimeout()</code>。 这个测试必须至少等待 JavaScript 引擎的一个周期，那个值才会变成可用状态。因此这个测试变成了<em>异步的</em>。</p><p translation-origin="off">You're not so lucky when testing the error path. Although the service spy will return an error synchronously, the component method calls <code>setTimeout()</code>. The test must wait at least one full turn of the JavaScript engine before the value becomes available. The test must become <em>asynchronous</em>.</p><a id="fake-async"></a><h4 id="async-test-with-fakeasync" translation-result="on">使用 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 进行异步测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#async-test-with-fakeasync"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="async-test-with-fakeasync">Async test with <em>fakeAsync()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#async-test-with-fakeasync"><i class="material-icons">link</i></a></h4><p translation-result="on">要使用 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 功能，你必须导入 <code>zone.js/dist/zone-testing</code>。 如果你是用 Angular CLI 创建的项目，那么 <code>src/test.ts</code> 中就已经导入好了 <code>zone-testing</code>。</p><p translation-origin="off">To use <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> functionality, you must import <code>zone.js/dist/zone-testing</code> in your test setup file. If you created your project with the Angular CLI, <code>zone-testing</code> is already imported in <code>src/test.ts</code>.</p><p translation-result="on">下列测试用于确保当服务返回 <code>ErrorObservable</code> 的时候也能有符合预期的行为。</p><p translation-origin="off">The following test confirms the expected behavior when the service returns an <code>ErrorObservable</code>.</p><code-example path="testing/src/app/twain/twain.component.spec.ts" region="error-test" ng-version="9.0.0-rc.11"><div style="display:none">it('should display error when TwainService fails', <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(() =&gt; { // tell spy to return an error observable getQuoteSpy.and.returnValue( throwError('TwainService test failure')); fixture.detectChanges(); // <a href="" class="code-anchor">onInit</a>() // sync spy errors immediately after init <a href="api/core/testing/tick" class="code-anchor">tick</a>(); // <a href="api/core/testing/flush" class="code-anchor">flush</a> the component's setTimeout() fixture.detectChanges(); // <a href="api/forms/NgModel#update" class="code-anchor">update</a> errorMessage within setTimeout() expect(errorMessage()).toMatch(/test failure/, 'should display error'); expect(quoteEl.textContent).toBe('...', 'should show placeholder'); }));</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should display error when TwainService fails'</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// tell spy to return an error observable</span><span class="pln">
  getQuoteSpy</span><span class="pun">.</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">returnValue</span><span class="pun">(</span><span class="pln">
    throwError</span><span class="pun">(</span><span class="str">'TwainService test failure'</span><span class="pun">));</span><span class="pln">

  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="" class="code-anchor"><span class="com">onInit</span></a><span class="com">()</span><span class="pln">
  </span><span class="com">// sync spy errors immediately after init</span><span class="pln">

  </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/core/testing/flush" class="code-anchor"><span class="com">flush</span></a><span class="com"> the component's setTimeout()</span><span class="pln">

  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/forms/NgModel#update" class="code-anchor"><span class="com">update</span></a><span class="com"> errorMessage within setTimeout()</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">errorMessage</span><span class="pun">()).</span><span class="pln">toMatch</span><span class="pun">(</span><span class="str">/test failure/</span><span class="pun">,</span><span class="pln"> </span><span class="str">'should display error'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'...'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'should show placeholder'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><p translation-result="on">注意这个 <code>it()</code> 函数接收了一个如下形式的参数。</p><p translation-origin="off">Note that the <code>it()</code> function receives an argument of the following form.</p><code-example language="javascript" ng-version="9.0.0-rc.11"><div style="display:none"><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(() =&gt; { /* test body */ })`</div><aio-code><pre class="lang-javascript prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">/* test body */</span><span class="pln"> </span><span class="pun">})`</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a></code> 函数通过在一个特殊的<em><code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a></code> 测试区域（zone）</em>中运行测试体来启用线性代码风格。 测试体看上去是同步的。 这里没有嵌套式语法（如 <code>Promise.then()</code>）来打断控制流。</p><p translation-origin="off">The <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> function enables a linear coding style by running the test body in a special <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a> test zone</code>. The test body appears to be synchronous. There is no nested syntax (like a <code>Promise.then()</code>) to disrupt the flow of control.</p><div class="alert is-helpful"><p translation-result="on">限制：如果测试体中发起了 <code>XMLHttpRequest</code>（XHR）调用，则 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 函数将不起作用。 测试中很少进行 XHR 调用，但是如果你需要调用 XHR，请参见下面的 <a href="guide/testing#async"><code>async()</code></a>部分。</p><p translation-origin="off">Limitation: The <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> function won't work if the test body makes an <code>XMLHttpRequest</code> (XHR) call. XHR calls within a test are rare, but if you need to call XHR, see <a href="guide/testing#async"><code>async()</code></a>, below.</p></div><a id="tick"></a><h4 id="the-tick-function" translation-result="on"><code><a href="api/core/ApplicationRef#tick" class="code-anchor">tick()</a></code> 函数<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-tick-function"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="the-tick-function">The <em>tick()</em> function<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-tick-function"><i class="material-icons">link</i></a></h4><p translation-result="on">你必须调用 <code><a href="api/core/ApplicationRef#tick" class="code-anchor">tick()</a></code> 函数来向前推动（虚拟）时钟。</p><p translation-origin="off">You do have to call <a href="api/core/testing/tick">tick()</a> to advance the (virtual) clock.</p><p translation-result="on">调用 <code><a href="api/core/ApplicationRef#tick" class="code-anchor">tick()</a></code> 会模拟时光的流逝，直到所有未决的异步活动都结束为止。 在这个例子中，它会等待错误处理器中的 <code>setTimeout()</code>。</p><p translation-origin="off">Calling <a href="api/core/testing/tick">tick()</a> simulates the passage of time until all pending asynchronous activities finish. In this case, it waits for the error handler's <code>setTimeout()</code>.</p><p translation-result="on"><code><a href="api/core/ApplicationRef#tick" class="code-anchor">tick()</a></code> 函数接受一个毫秒值作为参数（如果没有提供则默认为 0）。该参数表示虚拟时钟要前进多少。 比如，如果你的 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 测试中有一个 <code>setTimeout(fn, 100)</code> 函数，你就需要用 <code><a href="api/core/testing/tick" class="code-anchor">tick</a>(100)</code> 来触发它的 fn 回调。</p><p translation-origin="off">The <a href="api/core/testing/tick">tick()</a> function accepts milliseconds as a parameter (defaults to 0 if not provided). The parameter represents how much the virtual clock advances. For example, if you have a <code>setTimeout(fn, 100)</code> in a <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> test, you need to use tick(100) to trigger the fn callback.</p><code-example path="testing/src/app/demo/async-helper.spec.ts" region="fake-async-test-tick" ng-version="9.0.0-rc.11"><div style="display:none">it('should run timeout callback with delay after call <a href="api/core/testing/tick" class="code-anchor">tick</a> with millis', <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(() =&gt; { let called = false; setTimeout(() =&gt; { called = true; }, 100); <a href="api/core/testing/tick" class="code-anchor">tick</a>(100); expect(called).toBe(true); }));</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should run timeout callback with delay after call </span><a href="api/core/testing/tick" class="code-anchor"><span class="str">tick</span></a><span class="str"> with millis'</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">let</span><span class="pln"> called </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">false</span><span class="pun">;</span><span class="pln">
    setTimeout</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> called </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">;</span><span class="pln"> </span><span class="pun">},</span><span class="pln"> </span><span class="lit">100</span><span class="pun">);</span><span class="pln">
    </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">(</span><span class="lit">100</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">called</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code><a href="api/core/ApplicationRef#tick" class="code-anchor">tick()</a></code> 函数是你从 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 中导入的 Angular 测试实用工具之一。 它和 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 一同使用，并且你只能在 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 体中调用它。</p><p translation-origin="off">The <a href="api/core/testing/tick">tick()</a> function is one of the Angular testing utilities that you import with <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>. It's a companion to <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> and you can only call it within a <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> body.</p><h4 id="comparing-dates-inside-fakeasync" translation-result="on">在 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 中比较日期（date）<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#comparing-dates-inside-fakeasync"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="comparing-dates-inside-fakeasync">Comparing dates inside fakeAsync()<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#comparing-dates-inside-fakeasync"><i class="material-icons">link</i></a></h4><p translation-result="on"><code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 可以模拟时光的流逝，它允许你在 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 中计算日期之间的差异。</p><p translation-origin="off"><code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> simulates passage of time, which allows you to calculate the difference between dates inside <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code>.</p><code-example path="testing/src/app/demo/async-helper.spec.ts" region="fake-async-test-date" ng-version="9.0.0-rc.11"><div style="display:none">it('should get Date diff correctly in <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>', <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(() =&gt; { const start = Date.now(); <a href="api/core/testing/tick" class="code-anchor">tick</a>(100); const end = Date.now(); expect(end - start).toBe(100); }));</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should get Date diff correctly in </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="str">fakeAsync</span></a><span class="str">'</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> start </span><span class="pun">=</span><span class="pln"> </span><span class="typ">Date</span><span class="pun">.</span><span class="pln">now</span><span class="pun">();</span><span class="pln">
    </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">(</span><span class="lit">100</span><span class="pun">);</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> </span><span class="kwd">end</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="typ">Date</span><span class="pun">.</span><span class="pln">now</span><span class="pun">();</span><span class="pln">
    expect</span><span class="pun">(</span><span class="kwd">end</span><span class="pln"> </span><span class="pun">-</span><span class="pln"> start</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">100</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><h4 id="jasmineclock-with-fakeasync" translation-result="on"><code>jasmine.clock</code> 与 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#jasmineclock-with-fakeasync"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="jasmineclock-with-fakeasync">jasmine.clock with fakeAsync()<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#jasmineclock-with-fakeasync"><i class="material-icons">link</i></a></h4><p translation-result="on">Jasmine 也提供了 <code>clock</code> 特性来模拟日期。在 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 方法内，Angular 会自动运行那些调用 <code>jasmine.clock().install()</code> 和调用 <code>jasmine.clock().uninstall()</code> 之间的测试。<code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 不是必须的，而且如果嵌套它会抛出错误。</p><p translation-origin="off">Jasmine also provides a <code>clock</code> feature to mock dates. Angular automatically runs tests that are run after <code>jasmine.clock().install()</code> is called inside a <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> method until <code>jasmine.clock().uninstall()</code> is called. <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> is not needed and throws an error if nested.</p><p translation-result="on">默认情况下，该特性是禁用的。要启用它，请在导入 <code>zone-testing</code> 之前设置一个全局标志。</p><p translation-origin="off">By default, this feature is disabled. To enable it, set a global flag before importing <code>zone-testing</code>.</p><p translation-result="on">如果你使用 Angular CLI，请在 <code>src/test.ts</code> 中配置此标志。</p><p translation-origin="off">If you use the Angular CLI, configure this flag in <code>src/test.ts</code>.</p><code-example ng-version="9.0.0-rc.11"><div style="display:none">(window as any)['__zone_symbol__fakeAsyncPatchLock'] = true; import 'zone.js/dist/zone-testing';</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pun">(</span><span class="pln">window </span><span class="kwd">as</span><span class="pln"> any</span><span class="pun">)[</span><span class="str">'__zone_symbol__fakeAsyncPatchLock'</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="str">'zone.js/dist/zone-testing'</span><span class="pun">;</span></code>
    </pre></aio-code></code-example><code-example path="testing/src/app/demo/async-helper.spec.ts" region="fake-async-test-clock" ng-version="9.0.0-rc.11"><div style="display:none">describe('use jasmine.clock()', () =&gt; { // need to <a href="api/router/Router#config" class="code-anchor">config</a> __zone_symbol__fakeAsyncPatchLock flag // before loading zone.js/dist/zone-testing beforeEach(() =&gt; { jasmine.clock().install(); }); afterEach(() =&gt; { jasmine.clock().uninstall(); }); it('should auto enter <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>', () =&gt; { // is in <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a> now, don't need to call <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(testFn) let called = false; setTimeout(() =&gt; { called = true; }, 100); jasmine.clock().tick(100); expect(called).toBe(true); }); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">describe</span><span class="pun">(</span><span class="str">'use jasmine.clock()'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// need to </span><a href="api/router/Router#config" class="code-anchor"><span class="com">config</span></a><span class="com"> __zone_symbol__fakeAsyncPatchLock flag</span><span class="pln">
  </span><span class="com">// before loading zone.js/dist/zone-testing</span><span class="pln">
  beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="pln">clock</span><span class="pun">().</span><span class="pln">install</span><span class="pun">();</span><span class="pln"> </span><span class="pun">});</span><span class="pln">
  afterEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="pln">clock</span><span class="pun">().</span><span class="pln">uninstall</span><span class="pun">();</span><span class="pln"> </span><span class="pun">});</span><span class="pln">
  it</span><span class="pun">(</span><span class="str">'should auto enter </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="str">fakeAsync</span></a><span class="str">'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="com">// is in </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="com">fakeAsync</span></a><span class="com"> now, don't need to call </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="com">fakeAsync</span></a><span class="com">(testFn)</span><span class="pln">
    </span><span class="kwd">let</span><span class="pln"> called </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">false</span><span class="pun">;</span><span class="pln">
    setTimeout</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> called </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">;</span><span class="pln"> </span><span class="pun">},</span><span class="pln"> </span><span class="lit">100</span><span class="pun">);</span><span class="pln">
    jasmine</span><span class="pun">.</span><span class="pln">clock</span><span class="pun">().</span><span class="pln">tick</span><span class="pun">(</span><span class="lit">100</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">called</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><h4 id="using-the-rxjs-scheduler-inside-fakeasync" translation-result="on">在 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 内使用 RxJS 调度器（scheduler）<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#using-the-rxjs-scheduler-inside-fakeasync"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="using-the-rxjs-scheduler-inside-fakeasync">Using the RxJS scheduler inside fakeAsync()<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#using-the-rxjs-scheduler-inside-fakeasync"><i class="material-icons">link</i></a></h4><p translation-result="on">你还可以在 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 中使用 RxJS 调度器，就像 <code>setTimeout()</code> 或 <code>setInterval()</code> 一样，但是你要导入 <code>zone.js/dist/zone-patch-rxjs-fake-async</code> 来 patch 掉 RxJS 的调度器。</p><p translation-origin="off">You can also use RxJS scheduler in <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> just like using <code>setTimeout()</code> or <code>setInterval()</code>, but you need to import <code>zone.js/dist/zone-patch-rxjs-fake-async</code> to patch RxJS scheduler.</p><code-example path="testing/src/app/demo/async-helper.spec.ts" region="fake-async-test-rxjs" ng-version="9.0.0-rc.11"><div style="display:none">it('should get Date diff correctly in <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a> with rxjs scheduler', <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(() =&gt; { // need to add `import 'zone.js/dist/zone-patch-rxjs-fake-async' // to <a href="api/core/Version#patch" class="code-anchor">patch</a> rxjs scheduler let result = null; of ('hello').pipe(delay(1000)).subscribe(v =&gt; { result = v; }); expect(result).toBeNull(); <a href="api/core/testing/tick" class="code-anchor">tick</a>(1000); expect(result).toBe('hello'); const start = new Date().getTime(); let dateDiff = 0; interval(1000).pipe(take(2)).subscribe(() =&gt; dateDiff = (new Date().getTime() - start)); <a href="api/core/testing/tick" class="code-anchor">tick</a>(1000); expect(dateDiff).toBe(1000); <a href="api/core/testing/tick" class="code-anchor">tick</a>(1000); expect(dateDiff).toBe(2000); }));</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should get Date diff correctly in </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="str">fakeAsync</span></a><span class="str"> with rxjs scheduler'</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="com">// need to add `import 'zone.js/dist/zone-patch-rxjs-fake-async'</span><span class="pln">
    </span><span class="com">// to </span><a href="api/core/Version#patch" class="code-anchor"><span class="com">patch</span></a><span class="com"> rxjs scheduler</span><span class="pln">
    </span><span class="kwd">let</span><span class="pln"> result </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">;</span><span class="pln">
    of </span><span class="pun">(</span><span class="str">'hello'</span><span class="pun">).</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln">delay</span><span class="pun">(</span><span class="lit">1000</span><span class="pun">)).</span><span class="pln">subscribe</span><span class="pun">(</span><span class="pln">v </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> result </span><span class="pun">=</span><span class="pln"> v</span><span class="pun">;</span><span class="pln"> </span><span class="pun">});</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">result</span><span class="pun">).</span><span class="pln">toBeNull</span><span class="pun">();</span><span class="pln">
    </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">(</span><span class="lit">1000</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">result</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'hello'</span><span class="pun">);</span><span class="pln">

    </span><span class="kwd">const</span><span class="pln"> start </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Date</span><span class="pun">().</span><span class="pln">getTime</span><span class="pun">();</span><span class="pln">
    </span><span class="kwd">let</span><span class="pln"> dateDiff </span><span class="pun">=</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span><span class="pln">
    interval</span><span class="pun">(</span><span class="lit">1000</span><span class="pun">).</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln">take</span><span class="pun">(</span><span class="lit">2</span><span class="pun">)).</span><span class="pln">subscribe</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> dateDiff </span><span class="pun">=</span><span class="pln"> </span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Date</span><span class="pun">().</span><span class="pln">getTime</span><span class="pun">()</span><span class="pln"> </span><span class="pun">-</span><span class="pln"> start</span><span class="pun">));</span><span class="pln">

    </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">(</span><span class="lit">1000</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">dateDiff</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">1000</span><span class="pun">);</span><span class="pln">
    </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">(</span><span class="lit">1000</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">dateDiff</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">2000</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><h4 id="support-more-macrotasks" translation-result="on">支持更多宏任务（macroTasks）<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#support-more-macrotasks"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="support-more-macrotasks">Support more macroTasks<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#support-more-macrotasks"><i class="material-icons">link</i></a></h4><p translation-result="on">默认情况下，<code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 支持下列 <code>macroTasks</code>。</p><p translation-origin="off">By default <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> supports the following <code>macroTasks</code>.</p><ul><li>setTimeout</li><li>setInterval</li><li>requestAnimationFrame</li><li>webkitRequestAnimationFrame</li><li>mozRequestAnimationFrame</li></ul><p translation-result="on">如果你运行其它 <code>macroTasks</code>（比如 <code>HTMLCanvasElement.toBlob()</code>）就会抛出一条 <code>Unknown macroTask scheduled in fake <a href="api/core/testing/async" class="code-anchor">async</a> test</code> 错误。</p><p translation-origin="off">If you run other <code>macroTask</code> such as <code>HTMLCanvasElement.toBlob()</code>, <code>Unknown macroTask scheduled in fake <a href="api/core/testing/async" class="code-anchor">async</a> test</code> error will be thrown.</p><code-tabs ng-version="9.0.0-rc.11"><div style="display:none"><code-pane path="testing/src/app/shared/canvas.component.spec.ts" header="src/app/shared/canvas.component.spec.ts">import { <a href="api/core/testing/TestBed" class="code-anchor">TestBed</a>, <a href="api/core/testing/async" class="code-anchor">async</a>, <a href="api/core/testing/tick" class="code-anchor">tick</a>, <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a> } from '@angular/core/testing'; import { CanvasComponent } from './canvas.component'; describe('CanvasComponent', () =&gt; { beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { TestBed.configureTestingModule({ declarations: [ CanvasComponent ], }).compileComponents(); })); beforeEach(() =&gt; { window['__zone_symbol__FakeAsyncTestMacroTask'] = [ { source: 'HTMLCanvasElement.toBlob', callbackArgs: [{ size: 200 }] } ]; }); it('should be able to generate blob data from canvas', <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(() =&gt; { const fixture = TestBed.createComponent(CanvasComponent); fixture.detectChanges(); <a href="api/core/testing/tick" class="code-anchor">tick</a>(); const app = fixture.debugElement.componentInstance; expect(app.blobSize).toBeGreaterThan(0); })); });</code-pane><code-pane path="testing/src/app/shared/canvas.component.ts" header="src/app/shared/canvas.component.ts">import { <a href="api/core/Component" class="code-anchor">Component</a>, <a href="api/core/AfterViewInit" class="code-anchor">AfterViewInit</a>, <a href="api/core/ViewChild" class="code-anchor">ViewChild</a>, <a href="api/core/ElementRef" class="code-anchor">ElementRef</a> } from '@angular/core'; @<a href="api/core/Component" class="code-anchor">Component</a>({ selector: 'sample-canvas', template: '&lt;canvas #sampleCanvas width="200" height="200"&gt;&lt;/canvas&gt;' }) export class CanvasComponent implements <a href="api/core/AfterViewInit" class="code-anchor">AfterViewInit</a> { blobSize: number; @<a href="api/core/ViewChild" class="code-anchor">ViewChild</a>('sampleCanvas') sampleCanvas: <a href="api/core/ElementRef" class="code-anchor">ElementRef</a>; constructor() { } ngAfterViewInit() { const canvas = this.sampleCanvas.nativeElement; const context = canvas.getContext('2d'); if (context) { context.clearRect(0, 0, 200, 200); context.fillStyle = '#FF1122'; context.fillRect(0, 0, 200, 200); canvas.toBlob((blob: any) =&gt; { this.blobSize = blob.size; }); } } }</code-pane></div><mat-card class="mat-card"><mat-tab-group class="mat-tab-group code-tab-group mat-primary"><mat-tab-header class="mat-tab-header"><div aria-hidden="true" mat-ripple="" class="mat-ripple mat-tab-header-pagination mat-tab-header-pagination-before mat-elevation-z4 mat-tab-header-pagination-disabled"><div class="mat-tab-header-pagination-chevron"></div></div><div class="mat-tab-label-container"><div role="tablist" class="mat-tab-list" style="transform:translateX(0)"><div class="mat-tab-labels"><div role="tab" mattablabelwrapper="" mat-ripple="" cdkmonitorelementfocus="" class="mat-ripple mat-tab-label mat-tab-label-active ng-star-inserted" id="mat-tab-label-0-0" tabindex="0" aria-posinset="1" aria-setsize="2" aria-controls="mat-tab-content-0-0" aria-selected="true" aria-disabled="false"><div class="mat-tab-label-content"><span class="ng-star-inserted">src/app/shared/canvas.component.spec.ts</span></div></div><div role="tab" mattablabelwrapper="" mat-ripple="" cdkmonitorelementfocus="" class="mat-ripple mat-tab-label ng-star-inserted" id="mat-tab-label-0-1" tabindex="-1" aria-posinset="2" aria-setsize="2" aria-controls="mat-tab-content-0-1" aria-selected="false" aria-disabled="false"><div class="mat-tab-label-content"><span class="ng-star-inserted">src/app/shared/canvas.component.ts</span></div></div></div><mat-ink-bar class="mat-ink-bar" style="visibility:visible;left:0;width:310px"></mat-ink-bar></div></div><div aria-hidden="true" mat-ripple="" class="mat-ripple mat-tab-header-pagination mat-tab-header-pagination-after mat-elevation-z4 mat-tab-header-pagination-disabled"><div class="mat-tab-header-pagination-chevron"></div></div></mat-tab-header><div class="mat-tab-body-wrapper"><mat-tab-body role="tabpanel" class="mat-tab-body ng-tns-c50-2 mat-tab-body-active ng-star-inserted" id="mat-tab-content-0-0" aria-labelledby="mat-tab-label-0-0"><div class="mat-tab-body-content ng-tns-c50-2 ng-trigger ng-trigger-translateTab" style="transform:none"><aio-code class="ng-star-inserted" style=""><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from src/app/shared/canvas.component.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/testing/TestBed" class="code-anchor"><span class="typ">TestBed</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core/testing'</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">CanvasComponent</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'./canvas.component'</span><span class="pun">;</span><span class="pln">
describe</span><span class="pun">(</span><span class="str">'CanvasComponent'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
      declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
        </span><span class="typ">CanvasComponent</span><span class="pln">
      </span><span class="pun">],</span><span class="pln">
    </span><span class="pun">}).</span><span class="pln">compileComponents</span><span class="pun">();</span><span class="pln">
  </span><span class="pun">}));</span><span class="pln">
  beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    window</span><span class="pun">[</span><span class="str">'__zone_symbol__FakeAsyncTestMacroTask'</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
      </span><span class="pun">{</span><span class="pln">
        source</span><span class="pun">:</span><span class="pln"> </span><span class="str">'HTMLCanvasElement.toBlob'</span><span class="pun">,</span><span class="pln">
        callbackArgs</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[{</span><span class="pln"> size</span><span class="pun">:</span><span class="pln"> </span><span class="lit">200</span><span class="pln"> </span><span class="pun">}]</span><span class="pln">
      </span><span class="pun">}</span><span class="pln">
    </span><span class="pun">];</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
  it</span><span class="pun">(</span><span class="str">'should be able to generate blob data from canvas'</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">CanvasComponent</span><span class="pun">);</span><span class="pln">
    fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">
    </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">();</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> app </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">app</span><span class="pun">.</span><span class="pln">blobSize</span><span class="pun">).</span><span class="pln">toBeGreaterThan</span><span class="pun">(</span><span class="lit">0</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}));</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></div></mat-tab-body><mat-tab-body role="tabpanel" class="mat-tab-body ng-tns-c50-3 ng-star-inserted" id="mat-tab-content-0-1" aria-labelledby="mat-tab-label-0-1"><div class="mat-tab-body-content ng-tns-c50-3 ng-trigger ng-trigger-translateTab" style="transform:translate3d(100%,0,0);min-height:1px"></div></mat-tab-body></div></mat-tab-group></mat-card></code-tabs><p translation-result="on">如果你要支持这种情况，就要在 <code>beforeEach()</code> 中定义你要支持的 <code>macroTask</code>。比如：</p><p translation-origin="off">If you want to support such a case, you need to define the <code>macroTask</code> you want to support in <code>beforeEach()</code>. For example:</p><code-example language="javascript" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(() =&gt; { window['__zone_symbol__FakeAsyncTestMacroTask'] = [ { source: 'HTMLCanvasElement.toBlob', callbackArgs: [{ size: 200 }] } ]; }); it('toBlob should be able to run in <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>', <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(() =&gt; { const canvas: HTMLCanvasElement = document.getElementById('canvas') as HTMLCanvasElement; let blob = null; canvas.toBlob(function(b) { blob = b; }); <a href="api/core/testing/tick" class="code-anchor">tick</a>(); expect(blob.size).toBe(200); }) );</div><aio-code><pre class="lang-javascript prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  window</span><span class="pun">[</span><span class="str">'__zone_symbol__FakeAsyncTestMacroTask'</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
    </span><span class="pun">{</span><span class="pln">
      source</span><span class="pun">:</span><span class="pln"> </span><span class="str">'HTMLCanvasElement.toBlob'</span><span class="pun">,</span><span class="pln">
      callbackArgs</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[{</span><span class="pln"> size</span><span class="pun">:</span><span class="pln"> </span><span class="lit">200</span><span class="pln"> </span><span class="pun">}]</span><span class="pln">
    </span><span class="pun">}</span><span class="pln">
  </span><span class="pun">];</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'toBlob should be able to run in </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="str">fakeAsync</span></a><span class="str">'</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> canvas</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLCanvasElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> document</span><span class="pun">.</span><span class="pln">getElementById</span><span class="pun">(</span><span class="str">'canvas'</span><span class="pun">)</span><span class="pln"> as </span><span class="typ">HTMLCanvasElement</span><span class="pun">;</span><span class="pln">
    </span><span class="kwd">let</span><span class="pln"> blob </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">;</span><span class="pln">
    canvas</span><span class="pun">.</span><span class="pln">toBlob</span><span class="pun">(</span><span class="kwd">function</span><span class="pun">(</span><span class="pln">b</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
      blob </span><span class="pun">=</span><span class="pln"> b</span><span class="pun">;</span><span class="pln">
    </span><span class="pun">});</span><span class="pln">
    </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">();</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">blob</span><span class="pun">.</span><span class="pln">size</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">200</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">})</span><span class="pln">
</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><h4 id="async-observables" translation-result="on">异步的可观察对象<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#async-observables"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="async-observables">Async observables<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#async-observables"><i class="material-icons">link</i></a></h4><p translation-result="on">你可能对这些测试的覆盖率已经很满足了。</p><p translation-origin="off">You might be satisfied with the test coverage of these tests.</p><p translation-result="on">不过你可能会因为真实的服务没有按这种方式工作而困扰。 真实的服务器会把请求发送给远端服务器。 服务需要花一些时间来作出响应，它的响应当然也不会真的像前面两个测试中那样立即可用。</p><p translation-origin="off">However, you might be troubled by the fact that the real service doesn't quite behave this way. The real service sends requests to a remote server. A server takes time to respond and the response certainly won't be available immediately as in the previous two tests.</p><p translation-result="on">如果你在 <code>getQuote()</code> 间谍中返回一个<em>异步</em>可观察对象，那它就能更忠诚的反映出真实的世界了。</p><p translation-origin="off">Your tests will reflect the real world more faithfully if you return an <em>asynchronous</em> observable from the <code>getQuote()</code> spy like this.</p><code-example path="testing/src/app/twain/twain.component.spec.ts" region="async-setup" ng-version="9.0.0-rc.11"><div style="display:none">// Simulate delayed observable values with the `asyncData()` helper getQuoteSpy.and.returnValue(asyncData(testQuote));</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// Simulate delayed observable values with the `asyncData()` helper</span><span class="pln">
getQuoteSpy</span><span class="pun">.</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">returnValue</span><span class="pun">(</span><span class="pln">asyncData</span><span class="pun">(</span><span class="pln">testQuote</span><span class="pun">));</span></code>
    </pre></aio-code></code-example><h4 id="async-observable-helpers" translation-result="on">可观察对象的异步助手<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#async-observable-helpers"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="async-observable-helpers">Async observable helpers<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#async-observable-helpers"><i class="material-icons">link</i></a></h4><p translation-result="on">这个异步的可观察对象是用 <code>asyncData</code> 辅助函数生成的。 <code>asyncData</code> 助手是一个工具函数，你可以自己写一个，也可以从下面的范例代码中复制一份。</p><p translation-origin="off">The async observable was produced by an <code>asyncData</code> helper. The <code>asyncData</code> helper is a utility function that you'll have to write yourself, or you can copy this one from the sample code.</p><code-example path="testing/src/testing/async-observable-helpers.ts" region="async-data" header="testing/async-observable-helpers.ts" ng-version="9.0.0-rc.11"><div style="display:none">/** Create <a href="api/core/testing/async" class="code-anchor">async</a> observable that emits-once and completes * after a JS engine turn */ export function asyncData&lt;T&gt;(data: T) { return defer(() =&gt; Promise.resolve(data)); }</div><header class="ng-star-inserted">testing/async-observable-helpers.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from testing/async-observable-helpers.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">/** Create </span><a href="api/core/testing/async" class="code-anchor"><span class="com">async</span></a><span class="com"> observable that emits-once and completes
 *  after a JS engine turn */</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">function</span><span class="pln"> asyncData</span><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;(</span><span class="pln">data</span><span class="pun">:</span><span class="pln"> T</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> defer</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="typ">Promise</span><span class="pun">.</span><span class="pln">resolve</span><span class="pun">(</span><span class="pln">data</span><span class="pun">));</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">这个辅助函数的可观察对象会在 JavaScript 引擎的下一个工作周期中发出 <code>data</code> 的值。</p><p translation-origin="off">This helper's observable emits the <code>data</code> value in the next turn of the JavaScript engine.</p><p translation-result="on"><a href="http://reactivex.io/documentation/operators/defer.html">RxJS 的 <code>defer()</code> （延期）操作符</a> 会返回一个可观察对象。 它获取一个工厂函数，这个工厂函数或者返回 Promise 或者返回 Observable。 当有人订阅了这个 <code>defer</code> 的可观察对象时，它就会把这个订阅者添加到由那个工厂函数创建的新的可观察对象中。</p><p translation-origin="off">The <a href="http://reactivex.io/documentation/operators/defer.html">RxJS <code>defer()</code> operator</a> returns an observable. It takes a factory function that returns either a promise or an observable. When something subscribes to <em>defer</em>'s observable, it adds the subscriber to a new observable created with that factory.</p><p translation-result="on"><code>defer()</code> 操作符会把 <code>Promise.resolve()</code> 转换成一个新的可观察对象，然后像 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 那样的发出一个值，然后结束。 订阅者将会在接收到这个数据值之后自动被取消订阅。</p><p translation-origin="off">The <code>defer()</code> operator transforms the <code>Promise.resolve()</code> into a new observable that, like <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code>, emits once and completes. Subscribers are unsubscribed after they receive the data value.</p><p translation-result="on">下面是一个类似的用于产生异步错误的辅助函数。</p><p translation-origin="off">There's a similar helper for producing an async error.</p><code-example path="testing/src/testing/async-observable-helpers.ts" region="async-error" ng-version="9.0.0-rc.11"><div style="display:none">/** Create <a href="api/core/testing/async" class="code-anchor">async</a> observable error that errors * after a JS engine turn */ export function asyncError&lt;T&gt;(errorObject: any) { return defer(() =&gt; Promise.reject(errorObject)); }</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">/** Create </span><a href="api/core/testing/async" class="code-anchor"><span class="com">async</span></a><span class="com"> observable error that errors
 *  after a JS engine turn */</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">function</span><span class="pln"> asyncError</span><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;(</span><span class="pln">errorObject</span><span class="pun">:</span><span class="pln"> any</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> defer</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="typ">Promise</span><span class="pun">.</span><span class="pln">reject</span><span class="pun">(</span><span class="pln">errorObject</span><span class="pun">));</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><h4 id="more-async-tests" translation-result="on">更多异步测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#more-async-tests"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="more-async-tests">More async tests<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#more-async-tests"><i class="material-icons">link</i></a></h4><p translation-result="on">现在，<code>getQuote()</code> 间谍会返回一个异步的可观察对象，你的大多数测试也同样要变成异步的。</p><p translation-origin="off">Now that the <code>getQuote()</code> spy is returning async observables, most of your tests will have to be async as well.</p><p translation-result="on">下面这个 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 测试演示了你所期待的和真实世界中一样的数据流。</p><p translation-origin="off">Here's a <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> test that demonstrates the data flow you'd expect in the real world.</p><code-example path="testing/src/app/twain/twain.component.spec.ts" region="fake-async-test" ng-version="9.0.0-rc.11"><div style="display:none">it('should show quote after getQuote (<a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>)', <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(() =&gt; { fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).toBe('...', 'should show placeholder'); <a href="api/core/testing/tick" class="code-anchor">tick</a>(); // <a href="api/core/testing/flush" class="code-anchor">flush</a> the observable to get the quote fixture.detectChanges(); // <a href="api/forms/NgModel#update" class="code-anchor">update</a> view expect(quoteEl.textContent).toBe(testQuote, 'should show quote'); expect(errorMessage()).toBeNull('should not show error'); }));</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should show quote after getQuote (</span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="str">fakeAsync</span></a><span class="str">)'</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// ngOnInit()</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'...'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'should show placeholder'</span><span class="pun">);</span><span class="pln">

  </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/core/testing/flush" class="code-anchor"><span class="com">flush</span></a><span class="com"> the observable to get the quote</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/forms/NgModel#update" class="code-anchor"><span class="com">update</span></a><span class="com"> view</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">testQuote</span><span class="pun">,</span><span class="pln"> </span><span class="str">'should show quote'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">errorMessage</span><span class="pun">()).</span><span class="pln">toBeNull</span><span class="pun">(</span><span class="str">'should not show error'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><p translation-result="on">注意，这个 <code>&lt;quote&gt;</code> 元素应该在 <code>ngOnInit()</code> 之后显示占位值（<code>'...'</code>）， 但第一个引文却没有出现。</p><p translation-origin="off">Notice that the quote element displays the placeholder value (<code>'...'</code>) after <code>ngOnInit()</code>. The first quote hasn't arrived yet.</p><p translation-result="on">要刷出可观察对象中的第一个引文，你就要先调用 <code><a href="api/core/ApplicationRef#tick" class="code-anchor">tick()</a></code>，然后调用 <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code> 来要求 Angular 刷新屏幕。</p><p translation-origin="off">To flush the first quote from the observable, you call <a href="api/core/testing/tick">tick()</a>. Then call <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code> to tell Angular to update the screen.</p><p translation-result="on">然后你就可以断言这个 <code>&lt;quote&gt;</code> 元素应该显示所预期的文字了。</p><p translation-origin="off">Then you can assert that the quote element displays the expected text.</p><a id="async"></a><h4 id="async-test-with-async" translation-result="on">使用 <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 进行异步测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#async-test-with-async"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="async-test-with-async">Async test with <em>async()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#async-test-with-async"><i class="material-icons">link</i></a></h4><p translation-result="on">要使用 <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 功能，你必须导入 <code>zone.js/dist/zone-testing</code>。 如果你是用 Angular CLI 创建的项目，那么 <code>src/test.ts</code> 中就已经导入好了 <code>zone-testing</code>。</p><p translation-origin="off">To use <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> functionality, you must import <code>zone.js/dist/zone-testing</code> in your test setup file. If you created your project with the Angular CLI, <code>zone-testing</code> is already imported in <code>src/test.ts</code>.</p><p translation-result="on"><code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 工具函数有一些限制。 特别是，如果测试中发起了 <code>XMLHttpRequest</code>（XHR） 调用，它就没用了。 测试中的 <code>XHR</code> 调用比较罕见，所以你通常会使用 <a href="guide/testing#fake-async"><code>fakeAsync()</code></a>。 不过你可能迟早会需要调用 <code>XMLHttpRequest</code>，那就来了解一些 <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 的知识吧。</p><p translation-origin="off">The <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> utility function has a few limitations. In particular, it won't work if the test body makes an <code>XMLHttpRequest</code> (XHR) call. XHR calls within a test are rare so you can generally stick with <a href="guide/testing#fake-async"><code>fakeAsync()</code></a>. But if you ever do need to call <code>XMLHttpRequest</code>, you'll want to know about <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code>.</p><div class="alert is-helpful"><p translation-result="on"><code>TestBed.compileComponents()</code> 方法（参见<a href="guide/testing#compile-components">稍后</a>）就会在 JIT 编译期间调用 <code>XHR</code> 来读取外部模板和 CSS 文件。 如果写调用了 <code>compileComponents()</code> 的测试，就要用到 <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 工具函数了。</p><p translation-origin="off">The <code>TestBed.compileComponents()</code> method (see <a href="guide/testing#compile-components">below</a>) calls <code>XHR</code> to read external template and css files during "just-in-time" compilation. Write tests that call <code>compileComponents()</code> with the <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> utility.</p></div><p translation-result="on">下面是用 <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 工具函数重写的以前的 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 测试。</p><p translation-origin="off">Here's the previous <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> test, re-written with the <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> utility.</p><code-example path="testing/src/app/twain/twain.component.spec.ts" region="async-test" ng-version="9.0.0-rc.11"><div style="display:none">it('should show quote after getQuote (<a href="api/core/testing/async" class="code-anchor">async</a>)', <a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).toBe('...', 'should show placeholder'); fixture.whenStable().then(() =&gt; { // wait for <a href="api/core/testing/async" class="code-anchor">async</a> getQuote fixture.detectChanges(); // <a href="api/forms/NgModel#update" class="code-anchor">update</a> view with quote expect(quoteEl.textContent).toBe(testQuote); expect(errorMessage()).toBeNull('should not show error'); }); }));</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should show quote after getQuote (</span><a href="api/core/testing/async" class="code-anchor"><span class="str">async</span></a><span class="str">)'</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// ngOnInit()</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'...'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'should show placeholder'</span><span class="pun">);</span><span class="pln">

  fixture</span><span class="pun">.</span><span class="pln">whenStable</span><span class="pun">().</span><span class="kwd">then</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// wait for </span><a href="api/core/testing/async" class="code-anchor"><span class="com">async</span></a><span class="com"> getQuote</span><span class="pln">
    fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">        </span><span class="com">// </span><a href="api/forms/NgModel#update" class="code-anchor"><span class="com">update</span></a><span class="com"> view with quote</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">testQuote</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">errorMessage</span><span class="pun">()).</span><span class="pln">toBeNull</span><span class="pun">(</span><span class="str">'should not show error'</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 工具函数通过把测试人员的代码放进在一个特殊的<em>async 测试区域</em>中，节省了一些用于异步调用的样板代码。 你不必把 Jasmine 的 <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code> 传给这个测试，并在承诺（Promise）或可观察对象的回调中调用 <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code>。</p><p translation-origin="off">The <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> utility hides some asynchronous boilerplate by arranging for the tester's code to run in a special <em>async test zone</em>. You don't need to pass Jasmine's <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code> into the test and call <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code> because it is <code>undefined</code> in promise or observable callbacks.</p><p translation-result="on">但是对 <code>fixture.whenStable()</code> 的调用揭示了该测试的异步本性，它将会打破线性的控制流。</p><p translation-origin="off">But the test's asynchronous nature is revealed by the call to <code>fixture.whenStable()</code>, which breaks the linear flow of control.</p><p translation-result="on">当要在 <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 中使用 <code>setInterval()</code> 之类的 <code>intervalTimer()</code> 时，别忘了在测试完成之后调用 <code>clearInterval()</code> 来取消定时器，否则 <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 永远不会结束。</p><p translation-origin="off">When using an <code>intervalTimer()</code> such as <code>setInterval()</code> in <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code>, remember to cancel the timer with <code>clearInterval()</code> after the test, otherwise the <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> never ends.</p><a id="when-stable"></a><h4 id="whenstable"><em>whenStable</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#whenstable"><i class="material-icons">link</i></a></h4><p translation-result="on">该测试必须等待 <code>getQuote()</code> 的可观察对象发出下一条引言。 它不再调用 <code><a href="api/core/ApplicationRef#tick" class="code-anchor">tick()</a></code>，而是调用 <code>fixture.whenStable()</code>。</p><p translation-origin="off">The test must wait for the <code>getQuote()</code> observable to emit the next quote. Instead of calling <a href="api/core/testing/tick">tick()</a>, it calls <code>fixture.whenStable()</code>.</p><p translation-result="on"><code>fixture.whenStable()</code> 返回一个承诺，这个承诺会在 JavaScript 引擎的任务队列变为空白时被解析。 在这个例子中，一旦这个可观察对象发出了第一条引言，这个任务队列就会变为空。</p><p translation-origin="off">The <code>fixture.whenStable()</code> returns a promise that resolves when the JavaScript engine's task queue becomes empty. In this example, the task queue becomes empty when the observable emits the first quote.</p><p translation-result="on">该测试在这个承诺的回调中继续执行，它会调用 <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code> 来用预期的文本内容修改 <code>&lt;quote&gt;</code> 元素。</p><p translation-origin="off">The test resumes within the promise callback, which calls <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code> to update the quote element with the expected text.</p><a id="jasmine-done"></a><h4 id="jasmine-done">Jasmine <em>done()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#jasmine-done"><i class="material-icons">link</i></a></h4><p translation-result="on">虽然 <code><a href="api/core/testing/async" class="code-anchor">async</a></code> 和 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a></code> 函数极大地简化了 Angular 的异步测试，不过你仍然可以回退到传统的技术中。 也就是说给 <code>it</code> 额外传入一个函数型参数，这个函数接受一个 <a href="http://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support"><code>done</code> 回调</a>。</p><p translation-origin="off">While the <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> and <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> functions greatly simplify Angular asynchronous testing, you can still fall back to the traditional technique and pass <code>it</code> a function that takes a <a href="https://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support"><code>done</code> callback</a>.</p><p translation-result="on">但你不能在 <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 或 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 函数中调用 <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code>，因为它的 <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a></code> 参数是 <code>undefined</code>。</p><p translation-origin="off">You can't call <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code> in <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> or <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> functions, because the <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a> parameter</code> is <code>undefined</code>.</p><p translation-result="on">现在，你就要负责对 Promise 进行链接、处理错误，并在适当的时机调用 <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code> 了。</p><p translation-origin="off">Now you are responsible for chaining promises, handling errors, and calling <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code> at the appropriate moments.</p><p translation-result="on">写带有 <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code> 的测试函数会比 <code><a href="api/core/testing/async" class="code-anchor">async</a></code> 和 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a></code> 方式更加冗长。 不过有些时候它是必要的。 比如，你不能在那些涉及到 <code>intervalTimer()</code> 或 RxJS 的 <code>delay()</code> 操作符时调用 <code><a href="api/core/testing/async" class="code-anchor">async</a></code> 或 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a></code> 函数。</p><p translation-origin="off">Writing test functions with <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code>, is more cumbersome than <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code>and <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code>, but it is occasionally necessary when code involves the <code>intervalTimer()</code> like <code>setInterval</code>.</p><p translation-result="on">下面是对前面的测试用 <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code> 重写后的两个版本。 第一个会订阅由组件的 <code>quote</code> 属性暴露给模板的那个 <code>Observable</code>。</p><p translation-origin="off">Here are two more versions of the previous test, written with <code><a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>()</code>. The first one subscribes to the <code>Observable</code> exposed to the template by the component's <code>quote</code> property.</p><code-example path="testing/src/app/twain/twain.component.spec.ts" region="quote-done-test" ng-version="9.0.0-rc.11"><div style="display:none">it('should show last quote (quote <a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>)', (<a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>: DoneFn) =&gt; { fixture.detectChanges(); component.quote.pipe( last() ).subscribe(() =&gt; { fixture.detectChanges(); // <a href="api/forms/NgModel#update" class="code-anchor">update</a> view with quote expect(quoteEl.textContent).toBe(testQuote); expect(errorMessage()).toBeNull('should not show error'); <a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>(); }); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should show last quote (quote </span><a href="api/core/ApplicationInitStatus#done" class="code-anchor"><span class="str">done</span></a><span class="str">)'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">(</span><a href="api/core/ApplicationInitStatus#done" class="code-anchor"><span class="kwd">done</span></a><span class="pun">:</span><span class="pln"> </span><span class="typ">DoneFn</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">

  component</span><span class="pun">.</span><span class="pln">quote</span><span class="pun">.</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln"> </span><span class="kwd">last</span><span class="pun">()</span><span class="pln"> </span><span class="pun">).</span><span class="pln">subscribe</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/forms/NgModel#update" class="code-anchor"><span class="com">update</span></a><span class="com"> view with quote</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">testQuote</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">errorMessage</span><span class="pun">()).</span><span class="pln">toBeNull</span><span class="pun">(</span><span class="str">'should not show error'</span><span class="pun">);</span><span class="pln">
    </span><a href="api/core/ApplicationInitStatus#done" class="code-anchor"><span class="kwd">done</span></a><span class="pun">();</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">RxJS 的 <code>last()</code> 操作符会在结束之前发出这个可观察对象的最后一个值，也就是那条测试引文。 <code>subscribe</code> 回调中会像以前一样调用 <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code> 用这条测试引文更新 <code>&lt;quote&gt;</code> 元素。</p><p translation-origin="off">The RxJS <code>last()</code> operator emits the observable's last value before completing, which will be the test quote. The <code>subscribe</code> callback calls <code><a href="api/core/testing/ComponentFixture#detectChanges" class="code-anchor">detectChanges()</a></code> to update the quote element with the test quote, in the same manner as the earlier tests.</p><p translation-result="on">有些测试中，相对于在屏幕上展示了什么，你可能会更关心所注入服务的某个方法是如何被调用的，以及它的返回值是什么。</p><p translation-origin="off">In some tests, you're more interested in how an injected service method was called and what values it returned, than what appears on screen.</p><p translation-result="on">服务的间谍，比如假冒服务 <code>TwainService</code> 的 <code>getQuote()</code> 间谍，可以给你那些信息，并且对视图的状态做出断言。</p><p translation-origin="off">A service spy, such as the <code>qetQuote()</code> spy of the fake <code>TwainService</code>, can give you that information and make assertions about the state of the view.</p><code-example path="testing/src/app/twain/twain.component.spec.ts" region="spy-done-test" ng-version="9.0.0-rc.11"><div style="display:none">it('should show quote after getQuote (spy <a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>)', (<a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>: DoneFn) =&gt; { fixture.detectChanges(); // the spy's most recent call returns the observable with the test quote getQuoteSpy.calls.mostRecent().returnValue.subscribe(() =&gt; { fixture.detectChanges(); // <a href="api/forms/NgModel#update" class="code-anchor">update</a> view with quote expect(quoteEl.textContent).toBe(testQuote); expect(errorMessage()).toBeNull('should not show error'); <a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>(); }); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should show quote after getQuote (spy </span><a href="api/core/ApplicationInitStatus#done" class="code-anchor"><span class="str">done</span></a><span class="str">)'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">(</span><a href="api/core/ApplicationInitStatus#done" class="code-anchor"><span class="kwd">done</span></a><span class="pun">:</span><span class="pln"> </span><span class="typ">DoneFn</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">

  </span><span class="com">// the spy's most recent call returns the observable with the test quote</span><span class="pln">
  getQuoteSpy</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">mostRecent</span><span class="pun">().</span><span class="pln">returnValue</span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/forms/NgModel#update" class="code-anchor"><span class="com">update</span></a><span class="com"> view with quote</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">testQuote</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">errorMessage</span><span class="pun">()).</span><span class="pln">toBeNull</span><span class="pun">(</span><span class="str">'should not show error'</span><span class="pun">);</span><span class="pln">
    </span><a href="api/core/ApplicationInitStatus#done" class="code-anchor"><span class="kwd">done</span></a><span class="pun">();</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><hr><a id="marble-testing"></a><h3 id="component-marble-tests" translation-result="on">组件的弹珠测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-marble-tests"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="component-marble-tests">Component marble tests<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-marble-tests"><i class="material-icons">link</i></a></h3><p translation-result="on">前面的 <code>TwainComponent</code> 测试中使用 <code>TwainService</code> 中的 <code>asyncData</code> 和 <code>asyncError</code> 工具函数仿真了可观察对象的异步响应。</p><p translation-origin="off">The previous <code>TwainComponent</code> tests simulated an asynchronous observable response from the <code>TwainService</code> with the <code>asyncData</code> and <code>asyncError</code> utilities.</p><p translation-result="on">那些都是你自己写的简短函数。 很不幸，它们对于很多常见场景来说都太过简单了。 可观察对象通常会发出很多次值，还可能会在显著的延迟之后。 组件可能要协调多个由正常值和错误值组成的重叠序列的可观察对象。</p><p translation-origin="off">These are short, simple functions that you can write yourself. Unfortunately, they're too simple for many common scenarios. An observable often emits multiple times, perhaps after a significant delay. A component may coordinate multiple observables with overlapping sequences of values and errors.</p><p translation-result="on"><strong>RxJS 的弹珠测试</strong>是测试各种可观察对象场景的最佳方式 —— 无论简单还是复杂。 你可以看看<a href="http://rxmarbles.com/">弹珠图</a>，它揭示了可观察对象的工作原理。 弹珠测试使用类似的弹珠语言来在你的测试中指定可观察对象流和对它们的期待。</p><p translation-origin="off"><strong>RxJS marble testing</strong> is a great way to test observable scenarios, both simple and complex. You've likely seen the <a href="http://rxmarbles.com/">marble diagrams</a> that illustrate how observables work. Marble testing uses a similar marble language to specify the observable streams and expectations in your tests.</p><p translation-result="on">下面的例子使用弹珠测试重写了 <code>TwainComponent</code> 的两个测试。</p><p translation-origin="off">The following examples revisit two of the <code>TwainComponent</code> tests with marble testing.</p><p translation-result="on">首先安装 <code>jasmine-marbles</code> 这个 npm 包，然后倒入所需的符号。</p><p translation-origin="off">Start by installing the <code>jasmine-marbles</code> npm package. Then import the symbols you need.</p><code-example path="testing/src/app/twain/twain.component.marbles.spec.ts" region="import-marbles" header="app/twain/twain.component.marbles.spec.ts (import marbles)" ng-version="9.0.0-rc.11"><div style="display:none">import { cold, getTestScheduler } from 'jasmine-marbles';</div><header class="ng-star-inserted">app/twain/twain.component.marbles.spec.ts (import marbles)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/twain/twain.component.marbles.spec.ts (import marbles)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> cold</span><span class="pun">,</span><span class="pln"> getTestScheduler </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'jasmine-marbles'</span><span class="pun">;</span></code>
    </pre></aio-code></code-example><p translation-result="on">下面是对获取引文功能的完整测试：</p><p translation-origin="off">Here's the complete test for getting a quote:</p><code-example path="testing/src/app/twain/twain.component.marbles.spec.ts" region="get-quote-test" ng-version="9.0.0-rc.11"><div style="display:none">it('should show quote after getQuote (marbles)', () =&gt; { // observable test quote value and complete(), after delay const q$ = cold('---x|', { x: testQuote }); getQuoteSpy.and.returnValue( q$ ); fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).toBe('...', 'should show placeholder'); getTestScheduler().flush(); // <a href="api/core/testing/flush" class="code-anchor">flush</a> the observables fixture.detectChanges(); // <a href="api/forms/NgModel#update" class="code-anchor">update</a> view expect(quoteEl.textContent).toBe(testQuote, 'should show quote'); expect(errorMessage()).toBeNull('should not show error'); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should show quote after getQuote (marbles)'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// observable test quote value and complete(), after delay</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> q$ </span><span class="pun">=</span><span class="pln"> cold</span><span class="pun">(</span><span class="str">'---x|'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> x</span><span class="pun">:</span><span class="pln"> testQuote </span><span class="pun">});</span><span class="pln">
  getQuoteSpy</span><span class="pun">.</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">returnValue</span><span class="pun">(</span><span class="pln"> q$ </span><span class="pun">);</span><span class="pln">

  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// ngOnInit()</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'...'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'should show placeholder'</span><span class="pun">);</span><span class="pln">

  getTestScheduler</span><span class="pun">().</span><span class="pln">flush</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/core/testing/flush" class="code-anchor"><span class="com">flush</span></a><span class="com"> the observables</span><span class="pln">

  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/forms/NgModel#update" class="code-anchor"><span class="com">update</span></a><span class="com"> view</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">testQuote</span><span class="pun">,</span><span class="pln"> </span><span class="str">'should show quote'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">errorMessage</span><span class="pun">()).</span><span class="pln">toBeNull</span><span class="pun">(</span><span class="str">'should not show error'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">注意，这个 Jasmine 测试是同步的。没有调用 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code>。 弹珠测试使用了一个测试调度程序来用同步的方式模拟时间的流逝。</p><p translation-origin="off">Notice that the Jasmine test is synchronous. There's no <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code>. Marble testing uses a test scheduler to simulate the passage of time in a synchronous test.</p><p translation-result="on">弹珠测试的美妙之处在于它给出了可观察对象流的可视化定义。 这个测试定义了一个<a href="guide/testing#cold-observable"><em>冷的</em>可观察对象</a>，它等待三<a href="guide/testing#marble-frame">帧</a> (<code>---</code>)，然后发出一个值（<code>x</code>），然后结束（<code>|</code>）。 在第二个参数中，你把值标记（<code>x</code>）换成了实际发出的值（<code>testQuote</code>）。</p><p translation-origin="off">The beauty of marble testing is in the visual definition of the observable streams. This test defines a <a href="guide/testing#cold-observable"><em>cold</em> observable</a> that waits three <a href="guide/testing#marble-frame">frames</a> (<code>---</code>), emits a value (<code>x</code>), and completes (<code>|</code>). In the second argument you map the value marker (<code>x</code>) to the emitted value (<code>testQuote</code>).</p><code-example path="testing/src/app/twain/twain.component.marbles.spec.ts" region="test-quote-marbles" ng-version="9.0.0-rc.11"><div style="display:none">const q$ = cold('---x|', { x: testQuote });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">const</span><span class="pln"> q$ </span><span class="pun">=</span><span class="pln"> cold</span><span class="pun">(</span><span class="str">'---x|'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> x</span><span class="pun">:</span><span class="pln"> testQuote </span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">这个弹珠库会构造出相应的可观察对象，测试代码会把它当做 <code>getQuote</code> 间谍的返回值。</p><p translation-origin="off">The marble library constructs the corresponding observable, which the test sets as the <code>getQuote</code> spy's return value.</p><p translation-result="on">当你已经准备好激活这个弹珠库构造出的可观察对象时，只要让 <code>TestScheduler</code> 去<em>刷新</em>准备好的任务队列就可以了。代码如下：</p><p translation-origin="off">When you're ready to activate the marble observables, you tell the <code>TestScheduler</code> to <em>flush</em> its queue of prepared tasks like this.</p><code-example path="testing/src/app/twain/twain.component.marbles.spec.ts" region="test-scheduler-flush" ng-version="9.0.0-rc.11"><div style="display:none">getTestScheduler().flush(); // <a href="api/core/testing/flush" class="code-anchor">flush</a> the observables</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">getTestScheduler</span><span class="pun">().</span><span class="pln">flush</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/core/testing/flush" class="code-anchor"><span class="com">flush</span></a><span class="com"> the observables</span></code>
    </pre></aio-code></code-example><p translation-result="on">这个步骤的目的类似于前面的 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 和 <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 范例中的 <code><a href="api/core/ApplicationRef#tick" class="code-anchor">tick()</a></code> 和 <code>whenStable()</code>。 这种测试的权衡方式也和那些例子中是一样的。</p><p translation-origin="off">This step serves a purpose analogous to <a href="api/core/testing/tick">tick()</a> and <code>whenStable()</code> in the earlier <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> and <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> examples. The balance of the test is the same as those examples.</p><h4 id="marble-error-testing" translation-result="on">弹珠错误测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#marble-error-testing"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="marble-error-testing">Marble error testing<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#marble-error-testing"><i class="material-icons">link</i></a></h4><p translation-result="on">下面是 <code>getQuote()</code> 错误测试的弹珠测试版本。</p><p translation-origin="off">Here's the marble testing version of the <code>getQuote()</code> error test.</p><code-example path="testing/src/app/twain/twain.component.marbles.spec.ts" region="error-test" ng-version="9.0.0-rc.11"><div style="display:none">it('should display error when TwainService fails', <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(() =&gt; { // observable error after delay const q$ = cold('---#|', null, new Error('TwainService test failure')); getQuoteSpy.and.returnValue( q$ ); fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).toBe('...', 'should show placeholder'); getTestScheduler().flush(); // <a href="api/core/testing/flush" class="code-anchor">flush</a> the observables <a href="api/core/testing/tick" class="code-anchor">tick</a>(); // component shows error after a setTimeout() fixture.detectChanges(); // <a href="api/forms/NgModel#update" class="code-anchor">update</a> error <a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a> expect(errorMessage()).toMatch(/test failure/, 'should display error'); expect(quoteEl.textContent).toBe('...', 'should show placeholder'); }));</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should display error when TwainService fails'</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// observable error after delay</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> q$ </span><span class="pun">=</span><span class="pln"> cold</span><span class="pun">(</span><span class="str">'---#|'</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Error</span><span class="pun">(</span><span class="str">'TwainService test failure'</span><span class="pun">));</span><span class="pln">
  getQuoteSpy</span><span class="pun">.</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">returnValue</span><span class="pun">(</span><span class="pln"> q$ </span><span class="pun">);</span><span class="pln">

  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// ngOnInit()</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'...'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'should show placeholder'</span><span class="pun">);</span><span class="pln">

  getTestScheduler</span><span class="pun">().</span><span class="pln">flush</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/core/testing/flush" class="code-anchor"><span class="com">flush</span></a><span class="com"> the observables</span><span class="pln">
  </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">();</span><span class="pln">                     </span><span class="com">// component shows error after a setTimeout()</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">    </span><span class="com">// </span><a href="api/forms/NgModel#update" class="code-anchor"><span class="com">update</span></a><span class="com"> error </span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="com">message</span></a><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">errorMessage</span><span class="pun">()).</span><span class="pln">toMatch</span><span class="pun">(</span><span class="str">/test failure/</span><span class="pun">,</span><span class="pln"> </span><span class="str">'should display error'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">quoteEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'...'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'should show placeholder'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><p translation-result="on">它仍然是异步测试，要调用 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> 和 <code><a href="api/core/ApplicationRef#tick" class="code-anchor">tick()</a></code>，这是因为组件自身在处理错误的时候调用 <code>setTimeout()</code>。</p><p translation-origin="off">It's still an async test, calling <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> and <a href="api/core/testing/tick">tick()</a>, because the component itself calls <code>setTimeout()</code> when processing errors.</p><p translation-result="on">看看弹珠库生成的可观察对象的定义。</p><p translation-origin="off">Look at the marble observable definition.</p><code-example path="testing/src/app/twain/twain.component.marbles.spec.ts" region="error-marbles" ng-version="9.0.0-rc.11"><div style="display:none">const q$ = cold('---#|', null, new Error('TwainService test failure'));</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">const</span><span class="pln"> q$ </span><span class="pun">=</span><span class="pln"> cold</span><span class="pun">(</span><span class="str">'---#|'</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Error</span><span class="pun">(</span><span class="str">'TwainService test failure'</span><span class="pun">));</span></code>
    </pre></aio-code></code-example><p translation-result="on">它是一个<em>冷的</em>可观察对象，它等待三帧，然后发出一个错误。 井号（<code>#</code>）标记出了发出错误的时间点，这个错误是在第三个参数中指定的。 第二个参数是空的，因为这个可观察对象永远不会发出正常值。</p><p translation-origin="off">This is a <em>cold</em> observable that waits three frames and then emits an error, The hash (<code>#</code>) indicates the timing of the error that is specified in the third argument. The second argument is null because the observable never emits a value.</p><h4 id="learn-about-marble-testing" translation-result="on">深入学习弹珠测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#learn-about-marble-testing"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="learn-about-marble-testing">Learn about marble testing<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#learn-about-marble-testing"><i class="material-icons">link</i></a></h4><a id="marble-frame"></a><p translation-result="on"><em>弹珠帧</em>是测试时序中的虚拟单元。 每个符号（<code>-</code>，<code>x</code>，<code>|</code>，<code>#</code>）都表示一帧过去了。</p><p translation-origin="off">A <em>marble frame</em> is a virtual unit of testing time. Each symbol (<code>-</code>, <code>x</code>, <code>|</code>, <code>#</code>) marks the passing of one frame.</p><a id="cold-observable"></a><p translation-result="on"><em>冷的</em>可观察对象不会生成值，除非你订阅它。 应用中的大多数可观察对象都是冷的。 所有 <a href="guide/http"><code>HttpClient</code></a>的方法返回的都是冷的可观察对象。</p><p translation-origin="off">A <em>cold</em> observable doesn't produce values until you subscribe to it. Most of your application observables are cold. All <a href="guide/http"><em>HttpClient</em></a> methods return cold observables.</p><p translation-result="on"><em>热的</em>可观察对象在你订阅它之前就会生成值。 <a href="api/router/Router#events"><code>Router.events</code></a>可观察对象会主动汇报路由器的活动，它就是个<em>热的</em>可观察对象。</p><p translation-origin="off">A <em>hot</em> observable is already producing values <em>before</em> you subscribe to it. The <a href="api/router/Router#events"><em>Router.events</em></a> observable, which reports router activity, is a <em>hot</em> observable.</p><p translation-result="on">RxJS 的弹珠测试是一个内容丰富的主题，超出了本章的范围。 要想在网络上进一步学习它，可以从 <a href="https://github.com/ReactiveX/rxjs/blob/master/doc/writing-marble-tests.md">official documentation</a> 开始。</p><p translation-origin="off">RxJS marble testing is a rich subject, beyond the scope of this guide. Learn about it on the web, starting with the <a href="https://github.com/ReactiveX/rxjs/blob/master/doc/writing-marble-tests.md">official documentation</a>.</p><hr><a id="component-with-input-output"></a><h3 id="component-with-inputs-and-outputs" translation-result="on">带有输入输出参数的组件<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-with-inputs-and-outputs"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="component-with-inputs-and-outputs">Component with inputs and outputs<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-with-inputs-and-outputs"><i class="material-icons">link</i></a></h3><p translation-result="on">带有导入和导出的组件通常出现在宿主组件的视图模板中。 宿主使用属性绑定来设置输入属性，使用事件绑定来监听输出属性触发的事件。</p><p translation-origin="off">A component with inputs and outputs typically appears inside the view template of a host component. The host uses a property binding to set the input property and an event binding to listen to events raised by the output property.</p><p translation-result="on">测试的目的是验证这样的绑定和期待的那样正常工作。 测试程序应该设置导入值并监听导出事件。</p><p translation-origin="off">The testing goal is to verify that such bindings work as expected. The tests should set input values and listen for output events.</p><p translation-result="on"><code>DashboardHeroComponent</code> 是非常小的这种类型的例子组件。 它显示由 <code>DashboardCompoent</code> 提供的英雄个体。 点击英雄告诉 <code>DashbaordComponent</code> 用户已经选择了这个英雄。</p><p translation-origin="off">The <code>DashboardHeroComponent</code> is a tiny example of a component in this role. It displays an individual hero provided by the <code>DashboardComponent</code>. Clicking that hero tells the <code>DashboardComponent</code> that the user has selected the hero.</p><p translation-result="on"><code>DashboardHeroComponent</code> 是这样内嵌在 <code>DashboardCompoent</code> 的模板中的：</p><p translation-origin="off">The <code>DashboardHeroComponent</code> is embedded in the <code>DashboardComponent</code> template like this:</p><code-example path="testing/src/app/dashboard/dashboard.component.html" region="dashboard-hero" header="app/dashboard/dashboard.component.html (excerpt)" ng-version="9.0.0-rc.11"><div style="display:none">&lt;dashboard-hero *<a href="api/common/NgForOf" class="code-anchor">ngFor</a>="let hero of heroes" class="col-1-4" [hero]=hero (selected)="gotoDetail($event)" &gt; &lt;/dashboard-hero&gt;</div><header class="ng-star-inserted">app/dashboard/dashboard.component.html (excerpt)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard.component.html (excerpt)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="tag">&lt;dashboard-hero</span><span class="pln"> *</span><a href="api/common/NgForOf" class="code-anchor"><span class="atn">ngFor</span></a><span class="pun">=</span><span class="atv">"let hero of heroes"</span><span class="pln">  </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"col-1-4"</span><span class="pln">
  [</span><span class="atn">hero</span><span class="pln">]</span><span class="pun">=</span><span class="atv">hero</span><span class="pln">  (</span><span class="atn">selected</span><span class="pln">)</span><span class="pun">=</span><span class="atv">"gotoDetail($event)"</span><span class="pln"> </span><span class="tag">&gt;</span><span class="pln">
</span><span class="tag">&lt;/dashboard-hero&gt;</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>DashboardHeroComponent</code> 在 <code>*<a href="api/common/NgForOf" class="code-anchor">ngFor</a></code> 循环中出现，把每个组件的 <code>hero</code> input 属性设置为迭代的值，并监听组件的 <code>selected</code> 事件。</p><p translation-origin="off">The <code>DashboardHeroComponent</code> appears in an <code>*<a href="api/common/NgForOf" class="code-anchor">ngFor</a></code> repeater, which sets each component's <code>hero</code> input property to the looping value and listens for the component's <code>selected</code> event.</p><p translation-result="on">下面是该组件的完整定义：</p><p translation-origin="off">Here's the component's full definition:</p><a id="dashboard-hero-component"></a><code-example path="testing/src/app/dashboard/dashboard-hero.component.ts" region="component" header="app/dashboard/dashboard-hero.component.ts (component)" ng-version="9.0.0-rc.11"><div style="display:none">@<a href="api/core/Component" class="code-anchor">Component</a>({ selector: 'dashboard-hero', template: ` &lt;div (click)="click()" class="hero"&gt; {{hero.name | <a href="api/common/UpperCasePipe" class="code-anchor">uppercase</a>}} &lt;/div&gt;`, <a href="api/core/Component#styleUrls" class="code-anchor">styleUrls</a>: [ './dashboard-hero.component.css' ] }) export class DashboardHeroComponent { @<a href="api/core/Input" class="code-anchor">Input</a>() hero: Hero; @<a href="api/core/Output" class="code-anchor">Output</a>() selected = new <a href="api/core/EventEmitter" class="code-anchor">EventEmitter</a>&lt;Hero&gt;(); click() { this.selected.emit(this.hero); } }</div><header class="ng-star-inserted">app/dashboard/dashboard-hero.component.ts (component)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard-hero.component.ts (component)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">
  selector</span><span class="pun">:</span><span class="pln"> </span><span class="str">'dashboard-hero'</span><span class="pun">,</span><span class="pln">
  </span><span class="kwd">template</span><span class="pun">:</span><span class="pln"> </span><span class="str">`
    &lt;div (click)="click()" class="hero"&gt;
      {{hero.name | </span><a href="api/common/UpperCasePipe" class="code-anchor"><span class="str">uppercase</span></a><span class="str">}}
    &lt;/div&gt;`</span><span class="pun">,</span><span class="pln">
  </span><a href="api/core/Component#styleUrls" class="code-anchor"><span class="pln">styleUrls</span></a><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="str">'./dashboard-hero.component.css'</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">DashboardHeroComponent</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="lit">@</span><a href="api/core/Input" class="code-anchor"><span class="lit">Input</span></a><span class="pun">()</span><span class="pln"> hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">;</span><span class="pln">
  </span><span class="lit">@</span><a href="api/core/Output" class="code-anchor"><span class="lit">Output</span></a><span class="pun">()</span><span class="pln"> selected </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><a href="api/core/EventEmitter" class="code-anchor"><span class="typ">EventEmitter</span></a><span class="pun">&lt;</span><span class="typ">Hero</span><span class="pun">&gt;();</span><span class="pln">
  click</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">selected</span><span class="pun">.</span><span class="pln">emit</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">hero</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">虽然测试这么简单的组件没有什么内在价值，但是它的测试程序是值得学习的。 有下列候选测试方案：</p><p translation-origin="off">While testing a component this simple has little intrinsic value, it's worth knowing how. You can use one of these approaches:</p><ul><li><p translation-result="on">把它当作被 <code>DashbaordComponent</code> 使用的组件来测试</p><p translation-origin="off">Test it as used by <code>DashboardComponent</code>.</p></li><li><p translation-result="on">把它当作独立的组件来测试</p><p translation-origin="off">Test it as a stand-alone component.</p></li><li><p translation-result="on">把它当作被 <code>DashbaordComponent</code> 的替代组件使用的组件来测试</p><p translation-origin="off">Test it as used by a substitute for <code>DashboardComponent</code>.</p></li></ul><p translation-result="on">简单看看 <code>DashbaordComponent</code> 的构造函数就否决了第一种方案：</p><p translation-origin="off">A quick look at the <code>DashboardComponent</code> constructor discourages the first approach:</p><code-example path="testing/src/app/dashboard/dashboard.component.ts" region="ctor" header="app/dashboard/dashboard.component.ts (constructor)" ng-version="9.0.0-rc.11"><div style="display:none">constructor( private router: <a href="api/router/Router" class="code-anchor">Router</a>, private heroService: HeroService) { }</div><header class="ng-star-inserted">app/dashboard/dashboard.component.ts (constructor)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard.component.ts (constructor)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">constructor</span><span class="pun">(</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> router</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/Router" class="code-anchor"><span class="typ">Router</span></a><span class="pun">,</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> heroService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroService</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>DashbaordComponent</code> 依赖 Angular 路由器和 <code>HeroService</code> 服务。 你必须使用测试替身替换它们两个，似乎过于复杂了。 路由器尤其具有挑战性。</p><p translation-origin="off">The <code>DashboardComponent</code> depends on the Angular router and the <code>HeroService</code>. You'd probably have to replace them both with test doubles, which is a lot of work. The router seems particularly challenging.</p><div class="alert is-helpful"><p translation-result="on"><a href="guide/testing#routing-component">稍后的讨论</a>涵盖了那些需要路由器的测试组件。</p><p translation-origin="off">The <a href="guide/testing#routing-component">discussion below</a> covers testing components that require the router.</p></div><p translation-result="on">当前的任务是测试 <code>DashboardHeroComponent</code> 组件，而非 <code>DashbaordComponent</code>，所以无需做不必要的努力。 那就试试第二和第三种方案。</p><p translation-origin="off">The immediate goal is to test the <code>DashboardHeroComponent</code>, not the <code>DashboardComponent</code>, so, try the second and third options.</p><a id="dashboard-standalone"></a><h4 id="test-dashboardherocomponent-stand-alone" translation-result="on">单独测试 <code>DashboardHeroComponent</code><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#test-dashboardherocomponent-stand-alone"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="test-dashboardherocomponent-stand-alone">Test <em>DashboardHeroComponent</em> stand-alone<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#test-dashboardherocomponent-stand-alone"><i class="material-icons">link</i></a></h4><p translation-result="on">下面是 spec 文件的准备语句中的重点部分。</p><p translation-origin="off">Here's the meat of the spec file setup.</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.spec.ts" region="setup" header="app/dashboard/dashboard-hero.component.spec.ts (setup)" ng-version="9.0.0-rc.11"><div style="display:none">TestBed.configureTestingModule({ declarations: [ DashboardHeroComponent ] }) fixture = TestBed.createComponent(DashboardHeroComponent); comp = fixture.componentInstance; // find the hero's <a href="api/core/DebugElement" class="code-anchor">DebugElement</a> and element heroDe = fixture.debugElement.query(By.css('.hero')); heroEl = heroDe.nativeElement; // mock the hero supplied by the parent component expectedHero = { id: 42, name: 'Test Name' }; // simulate the parent setting the input property with that hero comp.hero = expectedHero; // <a href="api/animations/trigger" class="code-anchor">trigger</a> initial data binding fixture.detectChanges();</div><header class="ng-star-inserted">app/dashboard/dashboard-hero.component.spec.ts (setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard-hero.component.spec.ts (setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
  declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">DashboardHeroComponent</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">DashboardHeroComponent</span><span class="pun">);</span><span class="pln">
comp    </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">

</span><span class="com">// find the hero's </span><a href="api/core/DebugElement" class="code-anchor"><span class="com">DebugElement</span></a><span class="com"> and element</span><span class="pln">
heroDe  </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">.</span><span class="pln">query</span><span class="pun">(</span><span class="typ">By</span><span class="pun">.</span><span class="pln">css</span><span class="pun">(</span><span class="str">'.hero'</span><span class="pun">));</span><span class="pln">
heroEl </span><span class="pun">=</span><span class="pln"> heroDe</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">;</span><span class="pln">

</span><span class="com">// mock the hero supplied by the parent component</span><span class="pln">
expectedHero </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> id</span><span class="pun">:</span><span class="pln"> </span><span class="lit">42</span><span class="pun">,</span><span class="pln"> name</span><span class="pun">:</span><span class="pln"> </span><span class="str">'Test Name'</span><span class="pln"> </span><span class="pun">};</span><span class="pln">

</span><span class="com">// simulate the parent setting the input property with that hero</span><span class="pln">
comp</span><span class="pun">.</span><span class="pln">hero </span><span class="pun">=</span><span class="pln"> expectedHero</span><span class="pun">;</span><span class="pln">

</span><span class="com">// </span><a href="api/animations/trigger" class="code-anchor"><span class="com">trigger</span></a><span class="com"> initial data binding</span><span class="pln">
fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span></code>
    </pre></aio-code></code-example><p translation-result="on">注意代码是如何将模拟英雄（<code>expectedHero</code>）赋值给组件的 <code>hero</code> 属性的，模拟了 <code>DashbaordComponent</code> 在它的迭代器中通过属性绑定的赋值方式。</p><p translation-origin="off">Note how the setup code assigns a test hero (<code>expectedHero</code>) to the component's <code>hero</code> property, emulating the way the <code>DashboardComponent</code> would set it via the property binding in its repeater.</p><p translation-result="on">下面的测试会验证英雄的名字已经通过绑定的方式传播到模板中了。</p><p translation-origin="off">The following test verifies that the hero name is propagated to the template via a binding.</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.spec.ts" region="name-test" ng-version="9.0.0-rc.11"><div style="display:none">it('should display hero name in uppercase', () =&gt; { const expectedPipedName = expectedHero.name.toUpperCase(); expect(heroEl.textContent).toContain(expectedPipedName); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should display hero name in uppercase'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> expectedPipedName </span><span class="pun">=</span><span class="pln"> expectedHero</span><span class="pun">.</span><span class="pln">name</span><span class="pun">.</span><span class="pln">toUpperCase</span><span class="pun">();</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">heroEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="pln">expectedPipedName</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">因为<a href="guide/testing#dashboard-hero-component">模板</a>通过 Angular 的 <code><a href="api/common/UpperCasePipe" class="code-anchor">UpperCasePipe</a></code> 传入了英雄的名字，所以这个测试必须匹配该元素的值中包含了大写形式的名字。</p><p translation-origin="off">Because the <a href="guide/testing#dashboard-hero-component">template</a> passes the hero name through the Angular <code><a href="api/common/UpperCasePipe" class="code-anchor">UpperCasePipe</a></code>, the test must match the element value with the upper-cased name.</p><div class="alert is-helpful"><p translation-result="on">这个小测试示范了 Angular 的测试如何以较低的成本验证组件的视觉表现（它们不能通过<a href="guide/testing#component-class-testing">组件类测试</a>进行验证）。 而不用借助那些更慢、更复杂的端到端测试。</p><p translation-origin="off">This small test demonstrates how Angular tests can verify a component's visual representation—something not possible with <a href="guide/testing#component-class-testing">component class tests</a>—at low cost and without resorting to much slower and more complicated end-to-end tests.</p></div><h4 id="clicking" translation-result="on">点击<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#clicking"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="clicking">Clicking<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#clicking"><i class="material-icons">link</i></a></h4><p translation-result="on">点击这个英雄将会发出一个 <code>selected</code> 事件，而宿主元素（可能是 <code>DashboardComponent</code>）可能会听到它：</p><p translation-origin="off">Clicking the hero should raise a <code>selected</code> event that the host component (<code>DashboardComponent</code> presumably) can hear:</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.spec.ts" region="click-test" ng-version="9.0.0-rc.11"><div style="display:none">it('should raise selected event when clicked (triggerEventHandler)', () =&gt; { let selectedHero: Hero; comp.selected.subscribe((hero: Hero) =&gt; selectedHero = hero); heroDe.triggerEventHandler('click', null); expect(selectedHero).toBe(expectedHero); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should raise selected event when clicked (triggerEventHandler)'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> selectedHero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">;</span><span class="pln">
  comp</span><span class="pun">.</span><span class="pln">selected</span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">((</span><span class="pln">hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> selectedHero </span><span class="pun">=</span><span class="pln"> hero</span><span class="pun">);</span><span class="pln">

  heroDe</span><span class="pun">.</span><span class="pln">triggerEventHandler</span><span class="pun">(</span><span class="str">'click'</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">selectedHero</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">expectedHero</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">该组件的 <code>selected</code> 属性返回一个 <code><a href="api/core/EventEmitter" class="code-anchor">EventEmitter</a></code>，对消费者来说它和 RxJS 的同步 <code>Observable</code> 很像。 该测试会<em>显式</em>订阅它，而宿主组件会<em>隐式</em>订阅它。</p><p translation-origin="off">The component's <code>selected</code> property returns an <code><a href="api/core/EventEmitter" class="code-anchor">EventEmitter</a></code>, which looks like an RxJS synchronous <code>Observable</code> to consumers. The test subscribes to it <em>explicitly</em> just as the host component does <em>implicitly</em>.</p><p translation-result="on">如果该组件的行为符合预期，点击英雄所在的元素就会告诉组件的 <code>selected</code> 属性发出这个 <code>hero</code> 对象。</p><p translation-origin="off">If the component behaves as expected, clicking the hero's element should tell the component's <code>selected</code> property to emit the <code>hero</code> object.</p><p translation-result="on">这个测试会通过订阅 <code>selected</code> 来检测是否确实如此。</p><p translation-origin="off">The test detects that event through its subscription to <code>selected</code>.</p><a id="trigger-event-handler"></a><h4 id="triggereventhandler"><em>triggerEventHandler</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#triggereventhandler"><i class="material-icons">link</i></a></h4><p translation-result="on">前面测试中的 <code>heroDe</code> 是一个指向英雄条目 <code>&lt;div&gt;</code> 的 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code>。</p><p translation-origin="off">The <code>heroDe</code> in the previous test is a <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> that represents the hero <code>&lt;div&gt;</code>.</p><p translation-result="on">它有一些用于抽象与原生元素交互的 Angular 属性和方法。 这个测试会使用事件名称 <code>click</code> 来调用 <code>DebugElement.triggerEventHandler</code>。 <code>click</code> 的事件绑定到了 <code>DashboardHeroComponent.click()</code>。</p><p translation-origin="off">It has Angular properties and methods that abstract interaction with the native element. This test calls the <code>DebugElement.triggerEventHandler</code> with the "click" event name. The "click" event binding responds by calling <code>DashboardHeroComponent.click()</code>.</p><p translation-result="on">Angular 的 <code>DebugElement.triggerEventHandler</code> 可以用<strong>事件的名字</strong>触发<strong>任何数据绑定事件</strong>。 第二个参数是传给事件处理器的事件对象。</p><p translation-origin="off">The Angular <code>DebugElement.triggerEventHandler</code> can raise <em>any data-bound event</em> by its <em>event name</em>. The second parameter is the event object passed to the handler.</p><p translation-result="on">该测试使用事件对象 <code>null</code> 触发了一次 <code>click</code> 事件。</p><p translation-origin="off">The test triggered a "click" event with a <code>null</code> event object.</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.spec.ts" region="trigger-event-handler" ng-version="9.0.0-rc.11"><div style="display:none">heroDe.triggerEventHandler('click', null);</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">heroDe</span><span class="pun">.</span><span class="pln">triggerEventHandler</span><span class="pun">(</span><span class="str">'click'</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><p translation-result="on">测试程序假设（在这里应该这样)运行时间的事件处理器（组件的 <code>click()</code> 方法）不关心事件对象。</p><p translation-origin="off">The test assumes (correctly in this case) that the runtime event handler—the component's <code>click()</code> method—doesn't care about the event object.</p><div class="alert is-helpful"><p translation-result="on">其它处理器的要求比较严格。比如，<code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> 指令期望一个带有 <code>button</code> 属性的对象，该属性用于指出点击时按下的是哪个鼠标按钮。 如果不给出这个事件对象，<code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> 指令就会抛出一个错误。</p><p translation-origin="off">Other handlers are less forgiving. For example, the <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> directive expects an object with a <code>button</code> property that identifies which mouse button (if any) was pressed during the click. The <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> directive throws an error if the event object is missing.</p></div><h4 id="click-the-element" translation-result="on">点击该元素<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#click-the-element"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="click-the-element">Click the element<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#click-the-element"><i class="material-icons">link</i></a></h4><p translation-result="on">下面这个测试改为调用原生元素自己的 <code>click()</code> 方法，它对于<em>这个组件</em>来说相当完美。</p><p translation-origin="off">The following test alternative calls the native element's own <code>click()</code> method, which is perfectly fine for <em>this component</em>.</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.spec.ts" region="click-test-2" ng-version="9.0.0-rc.11"><div style="display:none">it('should raise selected event when clicked (element.click)', () =&gt; { let selectedHero: Hero; comp.selected.subscribe((hero: Hero) =&gt; selectedHero = hero); heroEl.click(); expect(selectedHero).toBe(expectedHero); });</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should raise selected event when clicked (element.click)'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> selectedHero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">;</span><span class="pln">
  comp</span><span class="pun">.</span><span class="pln">selected</span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">((</span><span class="pln">hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> selectedHero </span><span class="pun">=</span><span class="pln"> hero</span><span class="pun">);</span><span class="pln">

  heroEl</span><span class="pun">.</span><span class="pln">click</span><span class="pun">();</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">selectedHero</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">expectedHero</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><a id="click-helper"></a><h4 id="click-helper" translation-result="on"><em>click()</em> 辅助函数<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#click-helper"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="click-helper"><em>click()</em> helper<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#click-helper"><i class="material-icons">link</i></a></h4><p translation-result="on">点击按钮、链接或者任意 HTML 元素是很常见的测试任务。</p><p translation-origin="off">Clicking a button, an anchor, or an arbitrary HTML element is a common test task.</p><p translation-result="on">把<em>点击事件</em>的处理过程包装到如下的 <code>click()</code> 辅助函数中，可以让这项任务更一致、更简单：</p><p translation-origin="off">Make that consistent and easy by encapsulating the <em>click-triggering</em> process in a helper such as the <code>click()</code> function below:</p><code-example path="testing/src/testing/index.ts" region="click-event" header="testing/index.ts (click helper)" ng-version="9.0.0-rc.11"><div style="display:none">/** Button events to pass to `DebugElement.triggerEventHandler` for <a href="api/router/RouterLink" class="code-anchor">RouterLink</a> event handler */ export const ButtonClickEvents = { left: { button: 0 }, right: { button: 2 } }; /** Simulate element click. Defaults to mouse left-button click event. */ export function click(el: <a href="api/core/DebugElement" class="code-anchor">DebugElement</a> | HTMLElement, eventObj: any = ButtonClickEvents.left): void { if (el instanceof HTMLElement) { el.click(); } else { el.triggerEventHandler('click', eventObj); } }</div><header class="ng-star-inserted">testing/index.ts (click helper)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from testing/index.ts (click helper)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">/** Button events to pass to `DebugElement.triggerEventHandler` for </span><a href="api/router/RouterLink" class="code-anchor"><span class="com">RouterLink</span></a><span class="com"> event handler */</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">const</span><span class="pln"> </span><span class="typ">ButtonClickEvents</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
   left</span><span class="pun">:</span><span class="pln">  </span><span class="pun">{</span><span class="pln"> button</span><span class="pun">:</span><span class="pln"> </span><span class="lit">0</span><span class="pln"> </span><span class="pun">},</span><span class="pln">
   right</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> button</span><span class="pun">:</span><span class="pln"> </span><span class="lit">2</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
</span><span class="pun">};</span><span class="pln">

</span><span class="com">/** Simulate element click. Defaults to mouse left-button click event. */</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">function</span><span class="pln"> click</span><span class="pun">(</span><span class="pln">el</span><span class="pun">:</span><span class="pln"> </span><a href="api/core/DebugElement" class="code-anchor"><span class="typ">DebugElement</span></a><span class="pln"> </span><span class="pun">|</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pun">,</span><span class="pln"> eventObj</span><span class="pun">:</span><span class="pln"> any </span><span class="pun">=</span><span class="pln"> </span><span class="typ">ButtonClickEvents</span><span class="pun">.</span><span class="pln">left</span><span class="pun">):</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">el </span><span class="kwd">instanceof</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    el</span><span class="pun">.</span><span class="pln">click</span><span class="pun">();</span><span class="pln">
  </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">else</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    el</span><span class="pun">.</span><span class="pln">triggerEventHandler</span><span class="pun">(</span><span class="str">'click'</span><span class="pun">,</span><span class="pln"> eventObj</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">第一个参数是<strong>用来点击的元素</strong>。如果你愿意，可以将自定义的事件对象传给第二个参数。 默认的是（局部的）<a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button" target="_blank">鼠标左键事件对象</a>， 它被许多事件处理器接受，包括 <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> 指令。</p><p translation-origin="off">The first parameter is the <em>element-to-click</em>. If you wish, you can pass a custom event object as the second parameter. The default is a (partial) <a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button">left-button mouse event object</a> accepted by many handlers including the <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> directive.</p><div class="alert is-important"><p translation-result="on"><code>click()</code> 辅助函数<strong>不是</strong>Angular 测试工具之一。 它是在<strong>本章的例子代码</strong>中定义的函数方法，被所有测试例子所用。 如果你喜欢它，将它添加到你自己的辅助函数集。</p><p translation-origin="off">The <code>click()</code> helper function is <strong>not</strong> one of the Angular testing utilities. It's a function defined in <em>this guide's sample code</em>. All of the sample tests use it. If you like it, add it to your own collection of helpers.</p></div><p translation-result="on">下面是把前面的测试用 <code>click</code> 辅助函数重写后的版本。</p><p translation-origin="off">Here's the previous test, rewritten using the click helper.</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.spec.ts" region="click-test-3" header="app/dashboard/dashboard-hero.component.spec.ts (test with click helper)" ng-version="9.0.0-rc.11"><div style="display:none">it('should raise selected event when clicked (click helper)', () =&gt; { let selectedHero: Hero; comp.selected.subscribe((hero: Hero) =&gt; selectedHero = hero); click(heroDe); // click helper with <a href="api/core/DebugElement" class="code-anchor">DebugElement</a> click(heroEl); // click helper with <a href="" class="code-anchor">native</a> element expect(selectedHero).toBe(expectedHero); });</div><header class="ng-star-inserted">app/dashboard/dashboard-hero.component.spec.ts (test with click helper)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard-hero.component.spec.ts (test with click helper)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should raise selected event when clicked (click helper)'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> selectedHero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">;</span><span class="pln">
  comp</span><span class="pun">.</span><span class="pln">selected</span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">((</span><span class="pln">hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> selectedHero </span><span class="pun">=</span><span class="pln"> hero</span><span class="pun">);</span><span class="pln">

  click</span><span class="pun">(</span><span class="pln">heroDe</span><span class="pun">);</span><span class="pln"> </span><span class="com">// click helper with </span><a href="api/core/DebugElement" class="code-anchor"><span class="com">DebugElement</span></a><span class="pln">
  click</span><span class="pun">(</span><span class="pln">heroEl</span><span class="pun">);</span><span class="pln"> </span><span class="com">// click helper with </span><a href="" class="code-anchor"><span class="com">native</span></a><span class="com"> element</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">selectedHero</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">expectedHero</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><hr><a id="component-inside-test-host"></a><h3 id="component-inside-a-test-host" translation-result="on">位于测试宿主中的组件<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-inside-a-test-host"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="component-inside-a-test-host">Component inside a test host<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#component-inside-a-test-host"><i class="material-icons">link</i></a></h3><p translation-result="on">前面的这些测试都是自己扮演宿主元素 <code>DashboardComponent</code> 的角色。 但是当 <code>DashboardHeroComponent</code> 真的绑定到某个宿主元素时还能正常工作吗？</p><p translation-origin="off">The previous tests played the role of the host <code>DashboardComponent</code> themselves. But does the <code>DashboardHeroComponent</code> work correctly when properly data-bound to a host component?</p><p translation-result="on">固然，你也可以测试真实的 <code>DashboardComponent</code>。 但要想这么做需要做很多准备工作，特别是它的模板中使用了某些特性，如 <code>*<a href="api/common/NgForOf" class="code-anchor">ngFor</a></code>、 其它组件、布局 HTML、附加绑定、注入了多个服务的构造函数、如何用正确的方式与那些服务交互等。</p><p translation-origin="off">You could test with the actual <code>DashboardComponent</code>. But doing so could require a lot of setup, especially when its template features an <code>*<a href="api/common/NgForOf" class="code-anchor">ngFor</a></code> repeater, other components, layout HTML, additional bindings, a constructor that injects multiple services, and it starts interacting with those services right away.</p><p translation-result="on">想出这么多需要努力排除的干扰，只是为了证明一点 —— 可以造出这样一个令人满意的<em>测试宿主</em>：</p><p translation-origin="off">Imagine the effort to disable these distractions, just to prove a point that can be made satisfactorily with a <em>test host</em> like this one:</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.spec.ts" region="test-host" header="app/dashboard/dashboard-hero.component.spec.ts (test host)" ng-version="9.0.0-rc.11"><div style="display:none">@<a href="api/core/Component" class="code-anchor">Component</a>({ template: ` &lt;dashboard-hero [hero]="hero" (selected)="onSelected($event)"&gt; &lt;/dashboard-hero&gt;` }) class TestHostComponent { hero: Hero = {id: 42, name: 'Test Name' }; selectedHero: Hero; onSelected(hero: Hero) { this.selectedHero = hero; } }</div><header class="ng-star-inserted">app/dashboard/dashboard-hero.component.spec.ts (test host)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard-hero.component.spec.ts (test host)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">
  </span><span class="kwd">template</span><span class="pun">:</span><span class="pln"> </span><span class="str">`
    &lt;dashboard-hero
      [hero]="hero" (selected)="onSelected($event)"&gt;
    &lt;/dashboard-hero&gt;`</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">class</span><span class="pln"> </span><span class="typ">TestHostComponent</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">id</span><span class="pun">:</span><span class="pln"> </span><span class="lit">42</span><span class="pun">,</span><span class="pln"> name</span><span class="pun">:</span><span class="pln"> </span><span class="str">'Test Name'</span><span class="pln"> </span><span class="pun">};</span><span class="pln">
  selectedHero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">;</span><span class="pln">
  onSelected</span><span class="pun">(</span><span class="pln">hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">selectedHero </span><span class="pun">=</span><span class="pln"> hero</span><span class="pun">;</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">这个测试宿主像 <code>DashboardComponent</code> 那样绑定了 <code>DashboardHeroComponent</code>，但是没有 <code><a href="api/router/Router" class="code-anchor">Router</a></code>、 没有 <code>HeroService</code>，也没有 <code>*<a href="api/common/NgForOf" class="code-anchor">ngFor</a></code>。</p><p translation-origin="off">This test host binds to <code>DashboardHeroComponent</code> as the <code>DashboardComponent</code> would but without the noise of the <code><a href="api/router/Router" class="code-anchor">Router</a></code>, the <code>HeroService</code>, or the <code>*<a href="api/common/NgForOf" class="code-anchor">ngFor</a></code> repeater.</p><p translation-result="on">这个测试宿主使用其测试用的英雄设置了组件的输入属性 <code>hero</code>。 它使用 <code>onSelected</code> 事件处理器绑定了组件的 <code>selected</code> 事件，其中把事件中发出的英雄记录到了 <code>selectedHero</code> 属性中。</p><p translation-origin="off">The test host sets the component's <code>hero</code> input property with its test hero. It binds the component's <code>selected</code> event with its <code>onSelected</code> handler, which records the emitted hero in its <code>selectedHero</code> property.</p><p translation-result="on">稍后，这个测试就可以轻松检查 <code>selectedHero</code> 以验证 <code>DashboardHeroComponent.selected</code> 事件确实发出了所期望的英雄。</p><p translation-origin="off">Later, the tests will be able to easily check <code>selectedHero</code> to verify that the <code>DashboardHeroComponent.selected</code> event emitted the expected hero.</p><p translation-result="on">这个<em>测试宿主</em>中的准备代码和独立测试中的准备过程类似：</p><p translation-origin="off">The setup for the <em>test-host</em> tests is similar to the setup for the stand-alone tests:</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.spec.ts" region="test-host-setup" header="app/dashboard/dashboard-hero.component.spec.ts (test host setup)" ng-version="9.0.0-rc.11"><div style="display:none">TestBed.configureTestingModule({ declarations: [ DashboardHeroComponent, TestHostComponent ] }) // create TestHostComponent instead of DashboardHeroComponent fixture = TestBed.createComponent(TestHostComponent); testHost = fixture.componentInstance; heroEl = fixture.nativeElement.querySelector('.hero'); fixture.detectChanges(); // <a href="api/animations/trigger" class="code-anchor">trigger</a> initial data binding</div><header class="ng-star-inserted">app/dashboard/dashboard-hero.component.spec.ts (test host setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard-hero.component.spec.ts (test host setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
  declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">DashboardHeroComponent</span><span class="pun">,</span><span class="pln"> </span><span class="typ">TestHostComponent</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="com">// create TestHostComponent instead of DashboardHeroComponent</span><span class="pln">
fixture  </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">TestHostComponent</span><span class="pun">);</span><span class="pln">
testHost </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">
heroEl   </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'.hero'</span><span class="pun">);</span><span class="pln">
fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/animations/trigger" class="code-anchor"><span class="com">trigger</span></a><span class="com"> initial data binding</span></code>
    </pre></aio-code></code-example><p translation-result="on">这个测试模块的配置信息有三个重要的不同点：</p><p translation-origin="off">This testing module configuration shows three important differences:</p><ol><li><p translation-result="on">它同时<strong>声明</strong>了 <code>DashboardHeroComponent</code> 和 <code>TestHostComponent</code>。</p><p translation-origin="off">It <em>declares</em> both the <code>DashboardHeroComponent</code> and the <code>TestHostComponent</code>.</p></li><li><p translation-result="on">它<strong>创建</strong>了 <code>TestHostComponent</code>，而非 <code>DashboardHeroComponent</code>。</p><p translation-origin="off">It <em>creates</em> the <code>TestHostComponent</code> instead of the <code>DashboardHeroComponent</code>.</p></li><li><p translation-result="on"><code>TestHostComponent</code> 通过绑定机制设置了 <code>DashboardHeroComponent.hero</code>。</p><p translation-origin="off">The <code>TestHostComponent</code> sets the <code>DashboardHeroComponent.hero</code> with a binding.</p></li></ol><p translation-result="on"><code>createComponent</code> 返回的 <code>fixture</code> 里有 <code>TestHostComponent</code> 实例，而非 <code>DashboardHeroComponent</code> 组件实例。</p><p translation-origin="off">The <code>createComponent</code> returns a <code>fixture</code> that holds an instance of <code>TestHostComponent</code> instead of an instance of <code>DashboardHeroComponent</code>.</p><p translation-result="on">当然，创建 <code>TestHostComponent</code> 有创建 <code>DashboardHeroComponent</code> 的副作用，因为后者出现在前者的模板中。 英雄元素（<code>heroEl</code>)的查询语句仍然可以在测试 DOM 中找到它，尽管元素树比以前更深。</p><p translation-origin="off">Creating the <code>TestHostComponent</code> has the side-effect of creating a <code>DashboardHeroComponent</code> because the latter appears within the template of the former. The query for the hero element (<code>heroEl</code>) still finds it in the test DOM, albeit at greater depth in the element tree than before.</p><p translation-result="on">这些测试本身和它们的孤立版本几乎相同：</p><p translation-origin="off">The tests themselves are almost identical to the stand-alone version:</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.spec.ts" region="test-host-tests" header="app/dashboard/dashboard-hero.component.spec.ts (test-host)" ng-version="9.0.0-rc.11"><div style="display:none">it('should display hero name', () =&gt; { const expectedPipedName = testHost.hero.name.toUpperCase(); expect(heroEl.textContent).toContain(expectedPipedName); }); it('should raise selected event when clicked', () =&gt; { click(heroEl); // selected hero should be the same data bound hero expect(testHost.selectedHero).toBe(testHost.hero); });</div><header class="ng-star-inserted">app/dashboard/dashboard-hero.component.spec.ts (test-host)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard-hero.component.spec.ts (test-host)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should display hero name'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> expectedPipedName </span><span class="pun">=</span><span class="pln"> testHost</span><span class="pun">.</span><span class="pln">hero</span><span class="pun">.</span><span class="pln">name</span><span class="pun">.</span><span class="pln">toUpperCase</span><span class="pun">();</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">heroEl</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toContain</span><span class="pun">(</span><span class="pln">expectedPipedName</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should raise selected event when clicked'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  click</span><span class="pun">(</span><span class="pln">heroEl</span><span class="pun">);</span><span class="pln">
  </span><span class="com">// selected hero should be the same data bound hero</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">testHost</span><span class="pun">.</span><span class="pln">selectedHero</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">testHost</span><span class="pun">.</span><span class="pln">hero</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">只有 selected 事件的测试不一样。它确保被选择的 <code>DashboardHeroComponent</code> 英雄确实通过事件绑定被传递到宿主组件。</p><p translation-origin="off">Only the selected event test differs. It confirms that the selected <code>DashboardHeroComponent</code> hero really does find its way up through the event binding to the host component.</p><hr><a id="routing-component"></a><h3 id="routing-component" translation-result="on">路由组件<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#routing-component"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="routing-component">Routing component<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#routing-component"><i class="material-icons">link</i></a></h3><p translation-result="on">所谓<em>路由组件</em>就是指会要求 <code><a href="api/router/Router" class="code-anchor">Router</a></code> 导航到其它组件的组件。 <code>DashboardComponent</code> 就是一个<em>路由组件</em>，因为用户可以通过点击仪表盘中的某个<em>英雄按钮</em>来导航到 <code>HeroDetailComponent</code>。</p><p translation-origin="off">A <em>routing component</em> is a component that tells the <code><a href="api/router/Router" class="code-anchor">Router</a></code> to navigate to another component. The <code>DashboardComponent</code> is a <em>routing component</em> because the user can navigate to the <code>HeroDetailComponent</code> by clicking on one of the <em>hero buttons</em> on the dashboard.</p><p translation-result="on">路由确实很复杂。 测试 <code>DashboardComponent</code> 看上去有点令人生畏，因为它牵扯到和 <code>HeroService</code> 一起注入进来的 <code><a href="api/router/Router" class="code-anchor">Router</a></code>。</p><p translation-origin="off">Routing is pretty complicated. Testing the <code>DashboardComponent</code> seemed daunting in part because it involves the <code><a href="api/router/Router" class="code-anchor">Router</a></code>, which it injects together with the <code>HeroService</code>.</p><code-example path="testing/src/app/dashboard/dashboard.component.ts" region="ctor" header="app/dashboard/dashboard.component.ts (constructor)" ng-version="9.0.0-rc.11"><div style="display:none">constructor( private router: <a href="api/router/Router" class="code-anchor">Router</a>, private heroService: HeroService) { }</div><header class="ng-star-inserted">app/dashboard/dashboard.component.ts (constructor)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard.component.ts (constructor)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">constructor</span><span class="pun">(</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> router</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/Router" class="code-anchor"><span class="typ">Router</span></a><span class="pun">,</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> heroService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroService</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">使用间谍来 Mock <code>HeroService</code> 是一个<a href="guide/testing#component-with-async-service">熟悉的故事</a>。 但是 <code><a href="api/router/Router" class="code-anchor">Router</a></code> 的 API 很复杂，并且与其它服务和应用的前置条件纠缠在一起。它应该很难进行 Mock 吧？</p><p translation-origin="off">Mocking the <code>HeroService</code> with a spy is a <a href="guide/testing#component-with-async-service">familiar story</a>. But the <code><a href="api/router/Router" class="code-anchor">Router</a></code> has a complicated API and is entwined with other services and application preconditions. Might it be difficult to mock?</p><p translation-result="on">庆幸的是，在这个例子中不会，因为 <code>DashboardComponent</code> 并没有深度使用 <code><a href="api/router/Router" class="code-anchor">Router</a></code>。</p><p translation-origin="off">Fortunately, not in this case because the <code>DashboardComponent</code> isn't doing much with the <code><a href="api/router/Router" class="code-anchor">Router</a></code></p><code-example path="testing/src/app/dashboard/dashboard.component.ts" region="goto-detail" header="app/dashboard/dashboard.component.ts (goToDetail)" ng-version="9.0.0-rc.11"><div style="display:none">gotoDetail(hero: Hero) { let url = `/heroes/${hero.id}`; this.router.navigateByUrl(url); }</div><header class="ng-star-inserted">app/dashboard/dashboard.component.ts (goToDetail)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard.component.ts (goToDetail)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">gotoDetail</span><span class="pun">(</span><span class="pln">hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> url </span><span class="pun">=</span><span class="pln"> </span><span class="str">`/heroes/${hero.id}`</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">router</span><span class="pun">.</span><span class="pln">navigateByUrl</span><span class="pun">(</span><span class="pln">url</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">这是<em>路由组件</em>中的通例。 一般来说，你应该测试组件而不是路由器，应该只关心组件有没有根据给定的条件导航到正确的地址。</p><p translation-origin="off">This is often the case with <em>routing components</em>. As a rule you test the component, not the router, and care only if the component navigates with the right address under the given conditions.</p><p translation-result="on">为<em>这个组件</em>的测试套件提供路由器的间谍就像提供 <code>HeroService</code> 的间谍一样简单。</p><p translation-origin="off">Providing a router spy for <em>this component</em> test suite happens to be as easy as providing a <code>HeroService</code> spy.</p><code-example path="testing/src/app/dashboard/dashboard.component.spec.ts" region="router-spy" header="app/dashboard/dashboard.component.spec.ts (spies)" ng-version="9.0.0-rc.11"><div style="display:none">const routerSpy = jasmine.createSpyObj('<a href="api/router/Router" class="code-anchor">Router</a>', ['navigateByUrl']); const heroServiceSpy = jasmine.createSpyObj('HeroService', ['getHeroes']); TestBed.configureTestingModule({ providers: [ { provide: HeroService, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: heroServiceSpy }, { provide: <a href="api/router/Router" class="code-anchor">Router</a>, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: routerSpy } ] })</div><header class="ng-star-inserted">app/dashboard/dashboard.component.spec.ts (spies)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard.component.spec.ts (spies)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">const</span><span class="pln"> routerSpy </span><span class="pun">=</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="pln">createSpyObj</span><span class="pun">(</span><span class="str">'</span><a href="api/router/Router" class="code-anchor"><span class="str">Router</span></a><span class="str">'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">[</span><span class="str">'navigateByUrl'</span><span class="pun">]);</span><span class="pln">
</span><span class="kwd">const</span><span class="pln"> heroServiceSpy </span><span class="pun">=</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="pln">createSpyObj</span><span class="pun">(</span><span class="str">'HeroService'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">[</span><span class="str">'getHeroes'</span><span class="pun">]);</span><span class="pln">

</span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
  providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
    </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroService</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> heroServiceSpy </span><span class="pun">},</span><span class="pln">
    </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/Router" class="code-anchor"><span class="typ">Router</span></a><span class="pun">,</span><span class="pln">      </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> routerSpy </span><span class="pun">}</span><span class="pln">
  </span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span></code>
    </pre></aio-code></code-example><p translation-result="on">下面这个测试会点击正在显示的英雄，并确认 <code>Router.navigateByUrl</code> 曾用所期待的 URL 调用过。</p><p translation-origin="off">The following test clicks the displayed hero and confirms that <code>Router.navigateByUrl</code> is called with the expected url.</p><code-example path="testing/src/app/dashboard/dashboard.component.spec.ts" region="navigate-test" header="app/dashboard/dashboard.component.spec.ts (navigate test)" ng-version="9.0.0-rc.11"><div style="display:none">it('should tell ROUTER to navigate when hero clicked', () =&gt; { heroClick(); // <a href="api/animations/trigger" class="code-anchor">trigger</a> click on first inner &lt;div class="hero"&gt; // args passed to router.navigateByUrl() spy const spy = router.navigateByUrl as jasmine.Spy; const navArgs = spy.calls.first().args[0]; // expecting to navigate to id of the component's first hero const id = comp.heroes[0].id; expect(navArgs).toBe('/heroes/' + id, 'should nav to HeroDetail for first hero'); });</div><header class="ng-star-inserted">app/dashboard/dashboard.component.spec.ts (navigate test)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard.component.spec.ts (navigate test)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should tell ROUTER to navigate when hero clicked'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">

  heroClick</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/animations/trigger" class="code-anchor"><span class="com">trigger</span></a><span class="com"> click on first inner &lt;div class="hero"&gt;</span><span class="pln">

  </span><span class="com">// args passed to router.navigateByUrl() spy</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> spy </span><span class="pun">=</span><span class="pln"> router</span><span class="pun">.</span><span class="pln">navigateByUrl </span><span class="kwd">as</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="typ">Spy</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> navArgs </span><span class="pun">=</span><span class="pln"> spy</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">first</span><span class="pun">().</span><span class="pln">args</span><span class="pun">[</span><span class="lit">0</span><span class="pun">];</span><span class="pln">

  </span><span class="com">// expecting to navigate to id of the component's first hero</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> id </span><span class="pun">=</span><span class="pln"> comp</span><span class="pun">.</span><span class="pln">heroes</span><span class="pun">[</span><span class="lit">0</span><span class="pun">].</span><span class="pln">id</span><span class="pun">;</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">navArgs</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'/heroes/'</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> id</span><span class="pun">,</span><span class="pln">
    </span><span class="str">'should nav to HeroDetail for first hero'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><a id="routed-component-w-param"></a><h3 id="routed-components" translation-result="on">路由目标组件<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#routed-components"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="routed-components">Routed components<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#routed-components"><i class="material-icons">link</i></a></h3><p translation-result="on"><em>路由目标组件</em>是指 <code><a href="api/router/Router" class="code-anchor">Router</a></code> 导航到的目标。 它测试起来可能很复杂，特别是当路由到的这个组件<em>包含参数</em>的时候。 <code>HeroDetailComponent</code> 就是一个<em>路由目标组件</em>，它是某个路由定义指向的目标。</p><p translation-origin="off">A <em>routed component</em> is the destination of a <code><a href="api/router/Router" class="code-anchor">Router</a></code> navigation. It can be trickier to test, especially when the route to the component <em>includes parameters</em>. The <code>HeroDetailComponent</code> is a <em>routed component</em> that is the destination of such a route.</p><p translation-result="on">当用户点击<em>仪表盘</em>中的英雄时，<code>DashboardComponent</code> 会要求 <code><a href="api/router/Router" class="code-anchor">Router</a></code> 导航到 <code>heroes/:id</code>。 <code>:id</code> 是一个路由参数，它的值就是所要编辑的英雄的 <code>id</code>。</p><p translation-origin="off">When a user clicks a <em>Dashboard</em> hero, the <code>DashboardComponent</code> tells the <code><a href="api/router/Router" class="code-anchor">Router</a></code> to navigate to <code>heroes/:id</code>. The <code>:id</code> is a route parameter whose value is the <code>id</code> of the hero to edit.</p><p translation-result="on">该 <code><a href="api/router/Router" class="code-anchor">Router</a></code> 会根据那个 URL 匹配到一个指向 <code>HeroDetailComponent</code> 的路由。 它会创建一个带有路由信息的 <code><a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a></code> 对象，并把它注入到一个 <code>HeroDetailComponent</code> 的新实例中。</p><p translation-origin="off">The <code><a href="api/router/Router" class="code-anchor">Router</a></code> matches that URL to a route to the <code>HeroDetailComponent</code>. It creates an <code><a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a></code> object with the routing information and injects it into a new instance of the <code>HeroDetailComponent</code>.</p><p translation-result="on">下面是 <code>HeroDetailComponent</code> 的构造函数：</p><p translation-origin="off">Here's the <code>HeroDetailComponent</code> constructor:</p><code-example path="testing/src/app/hero/hero-detail.component.ts" region="ctor" header="app/hero/hero-detail.component.ts (constructor)" ng-version="9.0.0-rc.11"><div style="display:none">constructor( private heroDetailService: HeroDetailService, private route: <a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a>, private router: <a href="api/router/Router" class="code-anchor">Router</a>) { }</div><header class="ng-star-inserted">app/hero/hero-detail.component.ts (constructor)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.ts (constructor)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">constructor</span><span class="pun">(</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> heroDetailService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroDetailService</span><span class="pun">,</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> route</span><span class="pun">:</span><span class="pln">  </span><a href="api/router/ActivatedRoute" class="code-anchor"><span class="typ">ActivatedRoute</span></a><span class="pun">,</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> router</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/Router" class="code-anchor"><span class="typ">Router</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>HeroDetailComponent</code> 组件需要一个 <code>id</code> 参数，以便通过 <code>HeroDetailService</code> 获取相应的英雄。 该组件只能从 <code><a href="api/router/ActivatedRoute#paramMap" class="code-anchor">ActivatedRoute.paramMap</a></code> 属性中获取这个 <code>id</code>，这个属性是一个 <code>Observable</code>。</p><p translation-origin="off">The <code>HeroDetail</code> component needs the <code>id</code> parameter so it can fetch the corresponding hero via the <code>HeroDetailService</code>. The component has to get the <code>id</code> from the <code><a href="api/router/ActivatedRoute#paramMap" class="code-anchor">ActivatedRoute.paramMap</a></code> property which is an <code>Observable</code>.</p><p translation-result="on">它不能仅仅引用 <code><a href="api/router/ActivatedRoute#paramMap" class="code-anchor">ActivatedRoute.paramMap</a></code> 的 <code>id</code> 属性。 该组件不得不<em>订阅</em> <code><a href="api/router/ActivatedRoute#paramMap" class="code-anchor">ActivatedRoute.paramMap</a></code> 这个可观察对象，要做好它在生命周期中随时会发生变化的准备。</p><p translation-origin="off">It can't just reference the <code>id</code> property of the <code><a href="api/router/ActivatedRoute#paramMap" class="code-anchor">ActivatedRoute.paramMap</a></code>. The component has to <em>subscribe</em> to the <code><a href="api/router/ActivatedRoute#paramMap" class="code-anchor">ActivatedRoute.paramMap</a></code> observable and be prepared for the <code>id</code> to change during its lifetime.</p><code-example path="testing/src/app/hero/hero-detail.component.ts" region="ng-on-init" header="app/hero/hero-detail.component.ts (ngOnInit)" ng-version="9.0.0-rc.11"><div style="display:none">ngOnInit(): void { // get hero when `id` param <a href="api/core/QueryList#changes" class="code-anchor">changes</a> this.route.paramMap.subscribe(pmap =&gt; this.getHero(pmap.get('id'))); }</div><header class="ng-star-inserted">app/hero/hero-detail.component.ts (ngOnInit)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.ts (ngOnInit)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">ngOnInit</span><span class="pun">():</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// get hero when `id` param </span><a href="api/core/QueryList#changes" class="code-anchor"><span class="com">changes</span></a><span class="pln">
  </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">route</span><span class="pun">.</span><span class="pln">paramMap</span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">(</span><span class="pln">pmap </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">getHero</span><span class="pun">(</span><span class="pln">pmap</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><span class="str">'id'</span><span class="pun">)));</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><div class="alert is-helpful"><p translation-result="on"><a href="guide/router#route-parameters">路由与导航</a>一章中详细讲解了 <code><a href="api/router/ActivatedRoute#paramMap" class="code-anchor">ActivatedRoute.paramMap</a></code>。</p><p translation-origin="off">The <a href="guide/router#route-parameters">Router</a> guide covers <code><a href="api/router/ActivatedRoute#paramMap" class="code-anchor">ActivatedRoute.paramMap</a></code> in more detail.</p></div><p translation-result="on">通过操纵注入到组件构造函数中的这个 <code><a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a></code>，测试可以探查 <code>HeroDetailComponent</code> 是如何对不同的 <code>id</code> 参数值做出响应的。</p><p translation-origin="off">Tests can explore how the <code>HeroDetailComponent</code> responds to different <code>id</code> parameter values by manipulating the <code><a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a></code> injected into the component's constructor.</p><p translation-result="on">你已经知道了如何给 <code><a href="api/router/Router" class="code-anchor">Router</a></code> 和数据服务安插间谍。</p><p translation-origin="off">You know how to spy on the <code><a href="api/router/Router" class="code-anchor">Router</a></code> and a data service.</p><p translation-result="on">不过对于 <code><a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a></code>，你要采用另一种方式，因为：</p><p translation-origin="off">You'll take a different approach with <code><a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a></code> because</p><ul><li><p translation-result="on">在测试期间，<code>paramMap</code> 会返回一个能发出多个值的 <code>Observable</code>。</p><p translation-origin="off"><code>paramMap</code> returns an <code>Observable</code> that can emit more than one value during a test.</p></li><li><p translation-result="on">你需要路由器的辅助函数 <code><a href="api/router/convertToParamMap" class="code-anchor">convertToParamMap</a>()</code> 来创建 <code><a href="api/router/ParamMap" class="code-anchor">ParamMap</a></code>。</p><p translation-origin="off">You need the router helper function, <code><a href="api/router/convertToParamMap" class="code-anchor">convertToParamMap</a>()</code>, to create a <code><a href="api/router/ParamMap" class="code-anchor">ParamMap</a></code>.</p></li><li><p translation-result="on">针对<em>路由目标组件</em>的其它测试需要一个 <code><a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a></code> 的测试替身。</p><p translation-origin="off">Other <em>routed component</em> tests need a test double for <code><a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a></code>.</p></li></ul><p translation-result="on">这些差异表明你需要一个可复用的桩类（stub）。</p><p translation-origin="off">These differences argue for a re-usable stub class.</p><h4 id="activatedroutestub"><em>ActivatedRouteStub</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#activatedroutestub"><i class="material-icons">link</i></a></h4><p translation-result="on">下面的 <code>ActivatedRouteStub</code> 类就是作为 <code><a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a></code> 类的测试替身使用的。</p><p translation-origin="off">The following <code>ActivatedRouteStub</code> class serves as a test double for <code><a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a></code>.</p><code-example path="testing/src/testing/activated-route-stub.ts" region="activated-route-stub" header="testing/activated-route-stub.ts (ActivatedRouteStub)" ng-version="9.0.0-rc.11"><div style="display:none">import { <a href="api/router/convertToParamMap" class="code-anchor">convertToParamMap</a>, <a href="api/router/ParamMap" class="code-anchor">ParamMap</a>, <a href="api/router/Params" class="code-anchor">Params</a> } from '@angular/router'; import { ReplaySubject } from 'rxjs'; /** * An ActivateRoute test double with a `paramMap` observable. * Use the `setParamMap()` method to add the next `paramMap` value. */ export class ActivatedRouteStub { // Use a ReplaySubject to share <a href="api/service-worker/UpdateActivatedEvent#previous" class="code-anchor">previous</a> values with subscribers // and pump new values into the `paramMap` observable private subject = new ReplaySubject&lt;<a href="api/router/ParamMap" class="code-anchor">ParamMap</a>&gt;(); constructor(initialParams?: <a href="api/router/Params" class="code-anchor">Params</a>) { this.setParamMap(initialParams); } /** The mock paramMap observable */ readonly paramMap = this.subject.asObservable(); /** Set the paramMap observables's next value */ setParamMap(params?: <a href="api/router/Params" class="code-anchor">Params</a>) { this.subject.next(<a href="api/router/convertToParamMap" class="code-anchor">convertToParamMap</a>(params)); } }</div><header class="ng-star-inserted">testing/activated-route-stub.ts (ActivatedRouteStub)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from testing/activated-route-stub.ts (ActivatedRouteStub)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/router/convertToParamMap" class="code-anchor"><span class="pln">convertToParamMap</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/router/ParamMap" class="code-anchor"><span class="typ">ParamMap</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/router/Params" class="code-anchor"><span class="typ">Params</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/router'</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">ReplaySubject</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'rxjs'</span><span class="pun">;</span><span class="pln">

</span><span class="com">/**
 * An ActivateRoute test double with a `paramMap` observable.
 * Use the `setParamMap()` method to add the next `paramMap` value.
 */</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">ActivatedRouteStub</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// Use a ReplaySubject to share </span><a href="api/service-worker/UpdateActivatedEvent#previous" class="code-anchor"><span class="com">previous</span></a><span class="com"> values with subscribers</span><span class="pln">
  </span><span class="com">// and pump new values into the `paramMap` observable</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> subject </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">ReplaySubject</span><span class="pun">&lt;</span><a href="api/router/ParamMap" class="code-anchor"><span class="typ">ParamMap</span></a><span class="pun">&gt;();</span><span class="pln">

  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="pln">initialParams</span><span class="pun">?:</span><span class="pln"> </span><a href="api/router/Params" class="code-anchor"><span class="typ">Params</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">setParamMap</span><span class="pun">(</span><span class="pln">initialParams</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">

  </span><span class="com">/** The mock paramMap observable */</span><span class="pln">
  </span><span class="kwd">readonly</span><span class="pln"> paramMap </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">subject</span><span class="pun">.</span><span class="pln">asObservable</span><span class="pun">();</span><span class="pln">

  </span><span class="com">/** Set the paramMap observables's next value */</span><span class="pln">
  setParamMap</span><span class="pun">(</span><span class="kwd">params</span><span class="pun">?:</span><span class="pln"> </span><a href="api/router/Params" class="code-anchor"><span class="typ">Params</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">subject</span><span class="pun">.</span><span class="kwd">next</span><span class="pun">(</span><a href="api/router/convertToParamMap" class="code-anchor"><span class="pln">convertToParamMap</span></a><span class="pun">(</span><span class="kwd">params</span><span class="pun">));</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">考虑把这类辅助函数放进一个紧邻 <code>app</code> 文件夹的 <code>testing</code> 文件夹。 这个例子把 <code>ActivatedRouteStub</code> 放在了 <code>testing/activated-route-stub.ts</code> 中。</p><p translation-origin="off">Consider placing such helpers in a <code>testing</code> folder sibling to the <code>app</code> folder. This sample puts <code>ActivatedRouteStub</code> in <code>testing/activated-route-stub.ts</code>.</p><div class="alert is-helpful"><p translation-result="on">可以考虑使用<a href="guide/testing#marble-testing">弹珠测试库</a>来为此测试桩编写一个更强力的版本。</p><p translation-origin="off">Consider writing a more capable version of this stub class with the <a href="guide/testing#marble-testing"><em>marble testing library</em></a>.</p></div><a id="tests-w-test-double"></a><h4 id="testing-with-activatedroutestub" translation-result="on">使用 <code>ActivatedRouteStub</code> 进行测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-with-activatedroutestub"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="testing-with-activatedroutestub">Testing with <em>ActivatedRouteStub</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-with-activatedroutestub"><i class="material-icons">link</i></a></h4><p translation-result="on">下面的测试程序是演示组件在被观察的 <code>id</code> 指向现有英雄时的行为：</p><p translation-origin="off">Here's a test demonstrating the component's behavior when the observed <code>id</code> refers to an existing hero:</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="route-good-id" header="app/hero/hero-detail.component.spec.ts (existing id)" ng-version="9.0.0-rc.11"><div style="display:none">describe('when navigate to existing hero', () =&gt; { let expectedHero: Hero; beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { expectedHero = firstHero; activatedRoute.setParamMap({ id: expectedHero.id }); createComponent(); })); it('should display that hero\'s name', () =&gt; { expect(page.nameDisplay.textContent).toBe(expectedHero.name); }); });</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (existing id)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (existing id)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">describe</span><span class="pun">(</span><span class="str">'when navigate to existing hero'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> expectedHero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">;</span><span class="pln">

  beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    expectedHero </span><span class="pun">=</span><span class="pln"> firstHero</span><span class="pun">;</span><span class="pln">
    activatedRoute</span><span class="pun">.</span><span class="pln">setParamMap</span><span class="pun">({</span><span class="pln"> id</span><span class="pun">:</span><span class="pln"> expectedHero</span><span class="pun">.</span><span class="pln">id </span><span class="pun">});</span><span class="pln">
    createComponent</span><span class="pun">();</span><span class="pln">
  </span><span class="pun">}));</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'should display that hero\'s name'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">nameDisplay</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">expectedHero</span><span class="pun">.</span><span class="pln">name</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><div class="alert is-helpful"><p translation-result="on"><code>createComponent()</code> 方法和 <code>page</code> 对象会在<a href="guide/testing#page-object">稍后</a>进行讨论。 不过目前，你只要凭直觉来理解就行了。</p><p translation-origin="off">The <code>createComponent()</code> method and <code>page</code> object are discussed <a href="guide/testing#page-object">below</a>. Rely on your intuition for now.</p></div><p translation-result="on">当找不到 <code>id</code> 的时候，组件应该重新路由到 <code>HeroListComponent</code>。</p><p translation-origin="off">When the <code>id</code> cannot be found, the component should re-route to the <code>HeroListComponent</code>.</p><p translation-result="on">测试套件的准备代码提供了一个和<a href="guide/testing#routing-component">前面</a>一样的路由器间谍，它会充当路由器的角色，而不用发起实际的导航。</p><p translation-origin="off">The test suite setup provided the same router spy <a href="guide/testing#routing-component">described above</a> which spies on the router without actually navigating.</p><p translation-result="on">这个测试中会期待该组件尝试导航到 <code>HeroListComponent</code>。</p><p translation-origin="off">This test expects the component to try to navigate to the <code>HeroListComponent</code>.</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="route-bad-id" header="app/hero/hero-detail.component.spec.ts (bad id)" ng-version="9.0.0-rc.11"><div style="display:none">describe('when navigate to non-existent hero id', () =&gt; { beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { activatedRoute.setParamMap({ id: 99999 }); createComponent(); })); it('should try to navigate back to hero list', () =&gt; { expect(page.gotoListSpy.calls.any()).toBe(true, 'comp.gotoList called'); expect(page.navigateSpy.calls.any()).toBe(true, 'router.navigate called'); }); });</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (bad id)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (bad id)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">describe</span><span class="pun">(</span><span class="str">'when navigate to non-existent hero id'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    activatedRoute</span><span class="pun">.</span><span class="pln">setParamMap</span><span class="pun">({</span><span class="pln"> id</span><span class="pun">:</span><span class="pln"> </span><span class="lit">99999</span><span class="pln"> </span><span class="pun">});</span><span class="pln">
    createComponent</span><span class="pun">();</span><span class="pln">
  </span><span class="pun">}));</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'should try to navigate back to hero list'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">gotoListSpy</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">any</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">,</span><span class="pln"> </span><span class="str">'comp.gotoList called'</span><span class="pun">);</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">navigateSpy</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">any</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">,</span><span class="pln"> </span><span class="str">'router.navigate called'</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">虽然本应用没有在缺少 <code>id</code> 参数的时候，继续导航到 <code>HeroDetailComponent</code> 的路由，但是，将来它可能会添加这样的路由。 当没有 <code>id</code> 时，该组件应该作出合理的反应。</p><p translation-origin="off">While this app doesn't have a route to the <code>HeroDetailComponent</code> that omits the <code>id</code> parameter, it might add such a route someday. The component should do something reasonable when there is no <code>id</code>.</p><p translation-result="on">在本例中，组件应该创建和显示新英雄。 新英雄的 <code>id</code> 为零，<code>name</code> 为空。本测试程序确认组件是按照预期的这样做的：</p><p translation-origin="off">In this implementation, the component should create and display a new hero. New heroes have <code>id=0</code> and a blank <code>name</code>. This test confirms that the component behaves as expected:</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="route-no-id" header="app/hero/hero-detail.component.spec.ts (no id)" ng-version="9.0.0-rc.11"><div style="display:none">describe('when navigate with no hero id', () =&gt; { beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>( createComponent )); it('should have hero.id === 0', () =&gt; { expect(component.hero.id).toBe(0); }); it('should display empty hero name', () =&gt; { expect(page.nameDisplay.textContent).toBe(''); }); });</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (no id)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (no id)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">describe</span><span class="pun">(</span><span class="str">'when navigate with no hero id'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(</span><span class="pln"> createComponent </span><span class="pun">));</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'should have hero.id === 0'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">component</span><span class="pun">.</span><span class="pln">hero</span><span class="pun">.</span><span class="pln">id</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">0</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'should display empty hero name'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">nameDisplay</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">''</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><hr><h3 id="nested-component-tests" translation-result="on">对嵌套组件的测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#nested-component-tests"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="nested-component-tests">Nested component tests<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#nested-component-tests"><i class="material-icons">link</i></a></h3><p translation-result="on">组件的模板中通常还会有嵌套组件，嵌套组件的模板还可能包含更多组件。</p><p translation-origin="off">Component templates often have nested components, whose templates may contain more components.</p><p translation-result="on">这棵组件树可能非常深，并且大多数时候在测试这棵树顶部的组件时，这些嵌套的组件都无关紧要。</p><p translation-origin="off">The component tree can be very deep and, most of the time, the nested components play no role in testing the component at the top of the tree.</p><p translation-result="on">比如，<code>AppComponent</code> 会显示一个带有链接及其 <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> 指令的导航条。</p><p translation-origin="off">The <code>AppComponent</code>, for example, displays a navigation bar with anchors and their <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> directives.</p><code-example path="testing/src/app/app.component.html" header="app/app.component.html" ng-version="9.0.0-rc.11"><div style="display:none">&lt;app-banner&gt;&lt;/app-banner&gt; &lt;app-welcome&gt;&lt;/app-welcome&gt; &lt;nav&gt; &lt;a <a href="api/router/RouterLink" class="code-anchor">routerLink</a>="/dashboard"&gt;Dashboard&lt;/a&gt; &lt;a <a href="api/router/RouterLink" class="code-anchor">routerLink</a>="/heroes"&gt;Heroes&lt;/a&gt; &lt;a <a href="api/router/RouterLink" class="code-anchor">routerLink</a>="/about"&gt;About&lt;/a&gt; &lt;/nav&gt; &lt;<a href="api/router/RouterOutlet" class="code-anchor">router-outlet</a>&gt;&lt;/<a href="api/router/RouterOutlet" class="code-anchor">router-outlet</a>&gt;</div><header class="ng-star-inserted">app/app.component.html</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/app.component.html">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="tag">&lt;app-banner&gt;&lt;/app-banner&gt;</span><span class="pln">
</span><span class="tag">&lt;app-welcome&gt;&lt;/app-welcome&gt;</span><span class="pln">
</span><span class="tag">&lt;nav&gt;</span><span class="pln">
  </span><span class="tag">&lt;a</span><span class="pln"> </span><a href="api/router/RouterLink" class="code-anchor"><span class="atn">routerLink</span></a><span class="pun">=</span><span class="atv">"/dashboard"</span><span class="tag">&gt;</span><span class="pln">Dashboard</span><span class="tag">&lt;/a&gt;</span><span class="pln">
  </span><span class="tag">&lt;a</span><span class="pln"> </span><a href="api/router/RouterLink" class="code-anchor"><span class="atn">routerLink</span></a><span class="pun">=</span><span class="atv">"/heroes"</span><span class="tag">&gt;</span><span class="pln">Heroes</span><span class="tag">&lt;/a&gt;</span><span class="pln">
  </span><span class="tag">&lt;a</span><span class="pln"> </span><a href="api/router/RouterLink" class="code-anchor"><span class="atn">routerLink</span></a><span class="pun">=</span><span class="atv">"/about"</span><span class="tag">&gt;</span><span class="pln">About</span><span class="tag">&lt;/a&gt;</span><span class="pln">
</span><span class="tag">&lt;/nav&gt;</span><span class="pln">
</span><span class="tag">&lt;</span><a href="api/router/RouterOutlet" class="code-anchor"><span class="tag">router-outlet</span></a><span class="tag">&gt;&lt;/</span><a href="api/router/RouterOutlet" class="code-anchor"><span class="tag">router-outlet</span></a><span class="tag">&gt;</span></code>
    </pre></aio-code></code-example><p translation-result="on">虽然 <code>AppComponent</code> <em>类</em>是空的，不过，由于<a href="guide/testing#why-stubbed-routerlink-tests">稍后解释的原因</a>，你可能会希望写个单元测试来确认这些链接是否正确使用了 <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> 指令。</p><p translation-origin="off">While the <code>AppComponent</code> <em>class</em> is empty, you may want to write unit tests to confirm that the links are wired properly to the <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> directives, perhaps for the reasons <a href="guide/testing#why-stubbed-routerlink-tests">explained below</a>.</p><p translation-result="on">要想验证这些链接，你不必用 <code><a href="api/router/Router" class="code-anchor">Router</a></code> 进行导航，也不必使用 <code>&lt;<a href="api/router/RouterOutlet" class="code-anchor">router-outlet</a>&gt;</code> 来指出 <code><a href="api/router/Router" class="code-anchor">Router</a></code> 应该把<em>路由目标组件</em>插入到什么地方。</p><p translation-origin="off">To validate the links, you don't need the <code><a href="api/router/Router" class="code-anchor">Router</a></code> to navigate and you don't need the <code>&lt;<a href="api/router/RouterOutlet" class="code-anchor">router-outlet</a>&gt;</code> to mark where the <code><a href="api/router/Router" class="code-anchor">Router</a></code> inserts <em>routed components</em>.</p><p translation-result="on">而 <code>BannerComponent</code> 和 <code>WelcomeComponent</code>（写作 <code>&lt;app-banner&gt;</code> 和 <code>&lt;app-welcome&gt;</code>）也同样风马牛不相及。</p><p translation-origin="off">The <code>BannerComponent</code> and <code>WelcomeComponent</code> (indicated by <code>&lt;app-banner&gt;</code> and <code>&lt;app-welcome&gt;</code>) are also irrelevant.</p><p translation-result="on">然而，任何测试，只要能在 DOM 中创建 <code>AppComponent</code>，也就同样能创建这三个组件的实例。如果要创建它们，你就要配置 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>。</p><p translation-origin="off">Yet any test that creates the <code>AppComponent</code> in the DOM will also create instances of these three components and, if you let that happen, you'll have to configure the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> to create them.</p><p translation-result="on">如果你忘了声明它们，Angular 编译器就无法在 <code>AppComponent</code> 模板中识别出 <code>&lt;app-banner&gt;</code>、<code>&lt;app-welcome&gt;</code> 和 <code>&lt;<a href="api/router/RouterOutlet" class="code-anchor">router-outlet</a>&gt;</code> 标记，并抛出一个错误。</p><p translation-origin="off">If you neglect to declare them, the Angular compiler won't recognize the <code>&lt;app-banner&gt;</code>, <code>&lt;app-welcome&gt;</code>, and <code>&lt;<a href="api/router/RouterOutlet" class="code-anchor">router-outlet</a>&gt;</code> tags in the <code>AppComponent</code> template and will throw an error.</p><p translation-result="on">如果你声明的这些都是真实的组件，那么也同样要声明<em>它们</em>的嵌套组件，并要为这棵组件树中的<em>任何</em>组件提供要注入的<em>所有</em>服务。</p><p translation-origin="off">If you declare the real components, you'll also have to declare <em>their</em> nested components and provide for <em>all</em> services injected in <em>any</em> component in the tree.</p><p translation-result="on">如果只是想回答有关链接的一些简单问题，做这些显然就太多了。</p><p translation-origin="off">That's too much effort just to answer a few simple questions about links.</p><p translation-result="on">本节会讲减少此类准备工作的两项技术。 单独使用或组合使用它们，可以让这些测试聚焦于要测试的主要组件上。</p><p translation-origin="off">This section describes two techniques for minimizing the setup. Use them, alone or in combination, to stay focused on the testing the primary component.</p><a id="stub-component"></a><h5 id="stubbing-unneeded-components" translation-result="on">对不需要的组件提供桩（stub）<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#stubbing-unneeded-components"><i class="material-icons">link</i></a></h5><h5 translation-origin="off" id="stubbing-unneeded-components">Stubbing unneeded components<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#stubbing-unneeded-components"><i class="material-icons">link</i></a></h5><p translation-result="on">这项技术中，你要为那些在测试中无关紧要的组件或指令创建和声明一些测试桩。</p><p translation-origin="off">In the first technique, you create and declare stub versions of the components and directive that play little or no role in the tests.</p><code-example path="testing/src/app/app.component.spec.ts" region="component-stubs" header="app/app.component.spec.ts (stub declaration)" ng-version="9.0.0-rc.11"><div style="display:none">@<a href="api/core/Component" class="code-anchor">Component</a>({selector: 'app-banner', template: ''}) class BannerStubComponent {} @<a href="api/core/Component" class="code-anchor">Component</a>({selector: '<a href="api/router/RouterOutlet" class="code-anchor">router-outlet</a>', template: ''}) class RouterOutletStubComponent { } @<a href="api/core/Component" class="code-anchor">Component</a>({selector: 'app-welcome', template: ''}) class WelcomeStubComponent {}</div><header class="ng-star-inserted">app/app.component.spec.ts (stub declaration)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/app.component.spec.ts (stub declaration)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">selector</span><span class="pun">:</span><span class="pln"> </span><span class="str">'app-banner'</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">template</span><span class="pun">:</span><span class="pln"> </span><span class="str">''</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">class</span><span class="pln"> </span><span class="typ">BannerStubComponent</span><span class="pln"> </span><span class="pun">{}</span><span class="pln">

</span><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">selector</span><span class="pun">:</span><span class="pln"> </span><span class="str">'</span><a href="api/router/RouterOutlet" class="code-anchor"><span class="str">router-outlet</span></a><span class="str">'</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">template</span><span class="pun">:</span><span class="pln"> </span><span class="str">''</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">class</span><span class="pln"> </span><span class="typ">RouterOutletStubComponent</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">}</span><span class="pln">

</span><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">selector</span><span class="pun">:</span><span class="pln"> </span><span class="str">'app-welcome'</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">template</span><span class="pun">:</span><span class="pln"> </span><span class="str">''</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WelcomeStubComponent</span><span class="pln"> </span><span class="pun">{}</span></code>
    </pre></aio-code></code-example><p translation-result="on">这些测试桩的选择器要和其对应的真实组件一致，但其模板和类是空的。</p><p translation-origin="off">The stub selectors match the selectors for the corresponding real components. But their templates and classes are empty.</p><p translation-result="on">然后在 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 的配置中那些真正有用的组件、指令、管道之后声明它们。</p><p translation-origin="off">Then declare them in the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> configuration next to the components, directives, and pipes that need to be real.</p><code-example path="testing/src/app/app.component.spec.ts" region="testbed-stubs" header="app/app.component.spec.ts (TestBed stubs)" ng-version="9.0.0-rc.11"><div style="display:none">TestBed.configureTestingModule({ declarations: [ AppComponent, RouterLinkDirectiveStub, BannerStubComponent, RouterOutletStubComponent, WelcomeStubComponent ] })</div><header class="ng-star-inserted">app/app.component.spec.ts (TestBed stubs)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/app.component.spec.ts (TestBed stubs)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
  declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
    </span><span class="typ">AppComponent</span><span class="pun">,</span><span class="pln">
    </span><span class="typ">RouterLinkDirectiveStub</span><span class="pun">,</span><span class="pln">
    </span><span class="typ">BannerStubComponent</span><span class="pun">,</span><span class="pln">
    </span><span class="typ">RouterOutletStubComponent</span><span class="pun">,</span><span class="pln">
    </span><span class="typ">WelcomeStubComponent</span><span class="pln">
  </span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>AppComponent</code> 是该测试的主角，因此当然要用它的真实版本。</p><p translation-origin="off">The <code>AppComponent</code> is the test subject, so of course you declare the real version.</p><p translation-result="on">而 <code>RouterLinkDirectiveStub</code>（<a href="guide/testing#routerlink">稍后讲解</a>）是一个真实的 <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> 的测试版，它能帮你对链接进行测试。</p><p translation-origin="off">The <code>RouterLinkDirectiveStub</code>, <a href="guide/testing#routerlink">described later</a>, is a test version of the real <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> that helps with the link tests.</p><p translation-result="on">其它都是测试桩。</p><p translation-origin="off">The rest are stubs.</p><a id="no-errors-schema"></a><h4 id="no_errors_schema"><em>NO_ERRORS_SCHEMA</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#no_errors_schema"><i class="material-icons">link</i></a></h4><p translation-result="on">第二种办法就是把 <code><a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor">NO_ERRORS_SCHEMA</a></code> 添加到 <code>TestBed.schemas</code> 的元数据中。</p><p translation-origin="off">In the second approach, add <code><a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor">NO_ERRORS_SCHEMA</a></code> to the <code>TestBed.schemas</code> metadata.</p><code-example path="testing/src/app/app.component.spec.ts" region="no-errors-schema" header="app/app.component.spec.ts (NO_ERRORS_SCHEMA)" ng-version="9.0.0-rc.11"><div style="display:none">TestBed.configureTestingModule({ declarations: [ AppComponent, RouterLinkDirectiveStub ], schemas: [ <a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor">NO_ERRORS_SCHEMA</a> ] })</div><header class="ng-star-inserted">app/app.component.spec.ts (NO_ERRORS_SCHEMA)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/app.component.spec.ts (NO_ERRORS_SCHEMA)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
  declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
    </span><span class="typ">AppComponent</span><span class="pun">,</span><span class="pln">
    </span><span class="typ">RouterLinkDirectiveStub</span><span class="pln">
  </span><span class="pun">],</span><span class="pln">
  schemas</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor"><span class="pln">NO_ERRORS_SCHEMA</span></a><span class="pln"> </span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code><a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor">NO_ERRORS_SCHEMA</a></code> 会要求 Angular 编译器忽略不认识的那些元素和属性。</p><p translation-origin="off">The <code><a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor">NO_ERRORS_SCHEMA</a></code> tells the Angular compiler to ignore unrecognized elements and attributes.</p><p translation-result="on">编译器将会识别出 <code>&lt;app-root&gt;</code> 元素和 <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> 属性，因为你在 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 的配置中声明了相应的 <code>AppComponent</code> 和 <code>RouterLinkDirectiveStub</code>。</p><p translation-origin="off">The compiler will recognize the <code>&lt;app-root&gt;</code> element and the <code><a href="api/router/RouterLink" class="code-anchor">routerLink</a></code> attribute because you declared a corresponding <code>AppComponent</code> and <code>RouterLinkDirectiveStub</code> in the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> configuration.</p><p translation-result="on">但编译器在遇到 <code>&lt;app-banner&gt;</code>、<code>&lt;app-welcome&gt;</code> 或 <code>&lt;<a href="api/router/RouterOutlet" class="code-anchor">router-outlet</a>&gt;</code> 时不会报错。 它只会把它们渲染成空白标签，而浏览器会忽略这些标签。</p><p translation-origin="off">But the compiler won't throw an error when it encounters <code>&lt;app-banner&gt;</code>, <code>&lt;app-welcome&gt;</code>, or <code>&lt;<a href="api/router/RouterOutlet" class="code-anchor">router-outlet</a>&gt;</code>. It simply renders them as empty tags and the browser ignores them.</p><p translation-result="on">你不用再提供桩组件了。</p><p translation-origin="off">You no longer need the stub components.</p><h4 id="use-both-techniques-together" translation-result="on">同时使用这两项技术<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#use-both-techniques-together"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="use-both-techniques-together">Use both techniques together<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#use-both-techniques-together"><i class="material-icons">link</i></a></h4><p translation-result="on">这些是进行<em>浅层</em>测试要用到的技术，之所以叫浅层测试是因为只包含本测试所关心的这个组件模板中的元素。</p><p translation-origin="off">These are techniques for <em>Shallow Component Testing</em> , so-named because they reduce the visual surface of the component to just those elements in the component's template that matter for tests.</p><p translation-result="on"><code><a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor">NO_ERRORS_SCHEMA</a></code> 方法在这两者中比较简单，但也不要过度使用它。</p><p translation-origin="off">The <code><a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor">NO_ERRORS_SCHEMA</a></code> approach is the easier of the two but don't overuse it.</p><p translation-result="on"><code><a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor">NO_ERRORS_SCHEMA</a></code> 还会阻止编译器告诉你因为的疏忽或拼写错误而缺失的组件和属性。 你如果人工找出这些 bug 可能要浪费几个小时，但编译器可以立即捕获它们。</p><p translation-origin="off">The <code><a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor">NO_ERRORS_SCHEMA</a></code> also prevents the compiler from telling you about the missing components and attributes that you omitted inadvertently or misspelled. You could waste hours chasing phantom bugs that the compiler would have caught in an instant.</p><p translation-result="on"><em>桩组件</em>方式还有其它优点。 虽然<em>这个</em>例子中的桩是空的，但你如果想要和它们用某种形式互动，也可以给它们一些裁剪过的模板和类。</p><p translation-origin="off">The <em>stub component</em> approach has another advantage. While the stubs in <em>this</em> example were empty, you could give them stripped-down templates and classes if your tests need to interact with them in some way.</p><p translation-result="on">在实践中，你可以在准备代码中组合使用这两种技术，例子如下：</p><p translation-origin="off">In practice you will combine the two techniques in the same setup, as seen in this example.</p><code-example path="testing/src/app/app.component.spec.ts" region="mixed-setup" header="app/app.component.spec.ts (mixed setup)" ng-version="9.0.0-rc.11"><div style="display:none">TestBed.configureTestingModule({ declarations: [ AppComponent, BannerStubComponent, RouterLinkDirectiveStub ], schemas: [ <a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor">NO_ERRORS_SCHEMA</a> ] })</div><header class="ng-star-inserted">app/app.component.spec.ts (mixed setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/app.component.spec.ts (mixed setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
  declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
    </span><span class="typ">AppComponent</span><span class="pun">,</span><span class="pln">
    </span><span class="typ">BannerStubComponent</span><span class="pun">,</span><span class="pln">
    </span><span class="typ">RouterLinkDirectiveStub</span><span class="pln">
  </span><span class="pun">],</span><span class="pln">
  schemas</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor"><span class="pln">NO_ERRORS_SCHEMA</span></a><span class="pln"> </span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span></code>
    </pre></aio-code></code-example><p translation-result="on">Angular 编译器会为 <code>&lt;app-banner&gt;</code> 元素创建 <code>BannerComponentStub</code>，并把 <code>RouterLinkStubDirective</code> 应用到带有 <code><a href="api/router/RouterLink" class="code-anchor">routerLink</a></code> 属性的链接上，不过它会忽略 <code>&lt;app-welcome&gt;</code> 和 <code>&lt;<a href="api/router/RouterOutlet" class="code-anchor">router-outlet</a>&gt;</code> 标签。</p><p translation-origin="off">The Angular compiler creates the <code>BannerComponentStub</code> for the <code>&lt;app-banner&gt;</code> element and applies the <code>RouterLinkStubDirective</code> to the anchors with the <code><a href="api/router/RouterLink" class="code-anchor">routerLink</a></code> attribute, but it ignores the <code>&lt;app-welcome&gt;</code> and <code>&lt;<a href="api/router/RouterOutlet" class="code-anchor">router-outlet</a>&gt;</code> tags.</p><hr><a id="routerlink"></a><h3 id="components-with-routerlink" translation-result="on">带有 <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> 的组件<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#components-with-routerlink"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="components-with-routerlink">Components with <em>RouterLink</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#components-with-routerlink"><i class="material-icons">link</i></a></h3><p translation-result="on">真实的 <code>RouterLinkDirective</code> 太复杂了，而且与 <code><a href="api/router/RouterModule" class="code-anchor">RouterModule</a></code> 中的其它组件和指令有着千丝万缕的联系。 要在准备阶段 Mock 它以及在测试中使用它具有一定的挑战性。</p><p translation-origin="off">The real <code>RouterLinkDirective</code> is quite complicated and entangled with other components and directives of the <code><a href="api/router/RouterModule" class="code-anchor">RouterModule</a></code>. It requires challenging setup to mock and use in tests.</p><p translation-result="on">这段范例代码中的 <code>RouterLinkDirectiveStub</code> 用一个代用品替换了真实的指令，这个代用品用来验证 <code>AppComponent</code> 中所用链接的类型。</p><p translation-origin="off">The <code>RouterLinkDirectiveStub</code> in this sample code replaces the real directive with an alternative version designed to validate the kind of anchor tag wiring seen in the <code>AppComponent</code> template.</p><code-example path="testing/src/testing/router-link-directive-stub.ts" region="router-link" header="testing/router-link-directive-stub.ts (RouterLinkDirectiveStub)" ng-version="9.0.0-rc.11"><div style="display:none">@<a href="api/core/Directive" class="code-anchor">Directive</a>({ selector: '[<a href="api/router/RouterLink" class="code-anchor">routerLink</a>]' }) export class RouterLinkDirectiveStub { @<a href="api/core/Input" class="code-anchor">Input</a>('<a href="api/router/RouterLink" class="code-anchor">routerLink</a>') linkParams: any; navigatedTo: any = null; @<a href="api/core/HostListener" class="code-anchor">HostListener</a>('click') onClick() { this.navigatedTo = this.linkParams; } }</div><header class="ng-star-inserted">testing/router-link-directive-stub.ts (RouterLinkDirectiveStub)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from testing/router-link-directive-stub.ts (RouterLinkDirectiveStub)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Directive" class="code-anchor"><span class="lit">Directive</span></a><span class="pun">({</span><span class="pln">
  selector</span><span class="pun">:</span><span class="pln"> </span><span class="str">'[</span><a href="api/router/RouterLink" class="code-anchor"><span class="str">routerLink</span></a><span class="str">]'</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">RouterLinkDirectiveStub</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="lit">@</span><a href="api/core/Input" class="code-anchor"><span class="lit">Input</span></a><span class="pun">(</span><span class="str">'</span><a href="api/router/RouterLink" class="code-anchor"><span class="str">routerLink</span></a><span class="str">'</span><span class="pun">)</span><span class="pln"> linkParams</span><span class="pun">:</span><span class="pln"> any</span><span class="pun">;</span><span class="pln">
  navigatedTo</span><span class="pun">:</span><span class="pln"> any </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">;</span><span class="pln">

  </span><span class="lit">@</span><a href="api/core/HostListener" class="code-anchor"><span class="lit">HostListener</span></a><span class="pun">(</span><span class="str">'click'</span><span class="pun">)</span><span class="pln">
  onClick</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">navigatedTo </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">linkParams</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">这个 URL 被绑定到了 <code>[<a href="api/router/RouterLink" class="code-anchor">routerLink</a>]</code> 属性，它的值流入了该指令的 <code>linkParams</code> 属性。</p><p translation-origin="off">The URL bound to the <code>[<a href="api/router/RouterLink" class="code-anchor">routerLink</a>]</code> attribute flows in to the directive's <code>linkParams</code> property.</p><p translation-result="on">它的元数据中的 <code><a href="api/core/Directive#host" class="code-anchor">host</a></code> 属性把宿主元素（即 <code>AppComponent</code> 中的 <code>&lt;a&gt;</code> 元素）的 <code>click</code> 事件关联到了这个桩指令的 <code>onClick</code> 方法。</p><p translation-origin="off">The <code><a href="api/core/HostListener" class="code-anchor">HostListener</a></code> wires the click event of the host element (the <code>&lt;a&gt;</code> anchor elements in <code>AppComponent</code>) to the stub directive's <code>onClick</code> method.</p><p translation-result="on">点击这个链接应该触发 <code>onClick()</code> 方法，其中会设置该桩指令中的警示器属性 <code>navigatedTo</code>。 测试中检查 <code>navigatedTo</code> 以确认点击该链接确实如预期的那样根据路由定义设置了该属性。</p><p translation-origin="off">Clicking the anchor should trigger the <code>onClick()</code> method, which sets the stub's telltale <code>navigatedTo</code> property. Tests inspect <code>navigatedTo</code> to confirm that clicking the anchor set the expected route definition.</p><div class="alert is-helpful"><p translation-result="on">路由器的配置是否正确和是否能按照那些路由定义进行导航，是测试中一组独立的问题。</p><p translation-origin="off">Whether the router is configured properly to navigate with that route definition is a question for a separate set of tests.</p></div><a id="by-directive"></a> <a id="inject-directive"></a><h4 id="bydirective-and-injected-directives" translation-result="on"><code>By.directive</code> 与注入的指令<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#bydirective-and-injected-directives"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="bydirective-and-injected-directives"><em>By.directive</em> and injected directives<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#bydirective-and-injected-directives"><i class="material-icons">link</i></a></h4><p translation-result="on">再一步配置触发了数据绑定的初始化，获取导航链接的引用：</p><p translation-origin="off">A little more setup triggers the initial data binding and gets references to the navigation links:</p><code-example path="testing/src/app/app.component.spec.ts" region="test-setup" header="app/app.component.spec.ts (test setup)" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(() =&gt; { fixture.detectChanges(); // <a href="api/animations/trigger" class="code-anchor">trigger</a> initial data binding // find DebugElements with an attached RouterLinkStubDirective linkDes = fixture.debugElement .queryAll(By.directive(RouterLinkDirectiveStub)); // get attached link directive instances // using each <a href="api/core/DebugElement" class="code-anchor">DebugElement</a>'s injector routerLinks = linkDes.map(de =&gt; de.injector.get(RouterLinkDirectiveStub)); });</div><header class="ng-star-inserted">app/app.component.spec.ts (test setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/app.component.spec.ts (test setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// </span><a href="api/animations/trigger" class="code-anchor"><span class="com">trigger</span></a><span class="com"> initial data binding</span><span class="pln">

  </span><span class="com">// find DebugElements with an attached RouterLinkStubDirective</span><span class="pln">
  linkDes </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement
    </span><span class="pun">.</span><span class="pln">queryAll</span><span class="pun">(</span><span class="typ">By</span><span class="pun">.</span><span class="pln">directive</span><span class="pun">(</span><span class="typ">RouterLinkDirectiveStub</span><span class="pun">));</span><span class="pln">

  </span><span class="com">// get attached link directive instances</span><span class="pln">
  </span><span class="com">// using each </span><a href="api/core/DebugElement" class="code-anchor"><span class="com">DebugElement</span></a><span class="com">'s injector</span><span class="pln">
  routerLinks </span><span class="pun">=</span><span class="pln"> linkDes</span><span class="pun">.</span><span class="pln">map</span><span class="pun">(</span><span class="pln">de </span><span class="pun">=&gt;</span><span class="pln"> de</span><span class="pun">.</span><span class="pln">injector</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><span class="typ">RouterLinkDirectiveStub</span><span class="pun">));</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">有三点特别重要：</p><p translation-origin="off">Three points of special interest:</p><ol><li><p translation-result="on">你可以使用 <code>By.directive</code> 来定位一个带附属指令的链接元素。</p><p translation-origin="off">You can locate the anchor elements with an attached directive using <code>By.directive</code>.</p></li><li><p translation-result="on">该查询返回包含了匹配元素的 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 包装器。</p><p translation-origin="off">The query returns <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> wrappers around the matching elements.</p></li><li><p translation-result="on">每个 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 都会导出该元素中的一个依赖注入器，其中带有指定的指令实例。</p><p translation-origin="off">Each <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> exposes a dependency injector with the specific instance of the directive attached to that element.</p></li></ol><p translation-result="on"><code>AppComponent</code> 中要验证的链接如下：</p><p translation-origin="off">The <code>AppComponent</code> links to validate are as follows:</p><code-example path="testing/src/app/app.component.html" region="links" header="app/app.component.html (navigation links)" ng-version="9.0.0-rc.11"><div style="display:none">&lt;nav&gt; &lt;a <a href="api/router/RouterLink" class="code-anchor">routerLink</a>="/dashboard"&gt;Dashboard&lt;/a&gt; &lt;a <a href="api/router/RouterLink" class="code-anchor">routerLink</a>="/heroes"&gt;Heroes&lt;/a&gt; &lt;a <a href="api/router/RouterLink" class="code-anchor">routerLink</a>="/about"&gt;About&lt;/a&gt; &lt;/nav&gt;</div><header class="ng-star-inserted">app/app.component.html (navigation links)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/app.component.html (navigation links)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="tag">&lt;nav&gt;</span><span class="pln">
  </span><span class="tag">&lt;a</span><span class="pln"> </span><a href="api/router/RouterLink" class="code-anchor"><span class="atn">routerLink</span></a><span class="pun">=</span><span class="atv">"/dashboard"</span><span class="tag">&gt;</span><span class="pln">Dashboard</span><span class="tag">&lt;/a&gt;</span><span class="pln">
  </span><span class="tag">&lt;a</span><span class="pln"> </span><a href="api/router/RouterLink" class="code-anchor"><span class="atn">routerLink</span></a><span class="pun">=</span><span class="atv">"/heroes"</span><span class="tag">&gt;</span><span class="pln">Heroes</span><span class="tag">&lt;/a&gt;</span><span class="pln">
  </span><span class="tag">&lt;a</span><span class="pln"> </span><a href="api/router/RouterLink" class="code-anchor"><span class="atn">routerLink</span></a><span class="pun">=</span><span class="atv">"/about"</span><span class="tag">&gt;</span><span class="pln">About</span><span class="tag">&lt;/a&gt;</span><span class="pln">
</span><span class="tag">&lt;/nav&gt;</span></code>
    </pre></aio-code></code-example><a id="app-component-tests"></a><p translation-result="on">下面这些测试用来确认那些链接是否如预期般连接到了 <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> 指令中：</p><p translation-origin="off">Here are some tests that confirm those links are wired to the <code><a href="api/router/RouterLink" class="code-anchor">routerLink</a></code> directives as expected:</p><code-example path="testing/src/app/app.component.spec.ts" region="tests" header="app/app.component.spec.ts (selected tests)" ng-version="9.0.0-rc.11"><div style="display:none">it('can get RouterLinks from template', () =&gt; { expect(routerLinks.length).toBe(3, 'should have 3 routerLinks'); expect(routerLinks[0].linkParams).toBe('/dashboard'); expect(routerLinks[1].linkParams).toBe('/heroes'); expect(routerLinks[2].linkParams).toBe('/about'); }); it('can click Heroes link in template', () =&gt; { const heroesLinkDe = linkDes[1]; // heroes link <a href="api/core/DebugElement" class="code-anchor">DebugElement</a> const heroesLink = routerLinks[1]; // heroes link directive expect(heroesLink.navigatedTo).toBeNull('should not have <a href="api/router/Router#navigated" class="code-anchor">navigated</a> yet'); heroesLinkDe.triggerEventHandler('click', null); fixture.detectChanges(); expect(heroesLink.navigatedTo).toBe('/heroes'); });</div><header class="ng-star-inserted">app/app.component.spec.ts (selected tests)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/app.component.spec.ts (selected tests)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'can get RouterLinks from template'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">routerLinks</span><span class="pun">.</span><span class="pln">length</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">3</span><span class="pun">,</span><span class="pln"> </span><span class="str">'should have 3 routerLinks'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">routerLinks</span><span class="pun">[</span><span class="lit">0</span><span class="pun">].</span><span class="pln">linkParams</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'/dashboard'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">routerLinks</span><span class="pun">[</span><span class="lit">1</span><span class="pun">].</span><span class="pln">linkParams</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'/heroes'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">routerLinks</span><span class="pun">[</span><span class="lit">2</span><span class="pun">].</span><span class="pln">linkParams</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'/about'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'can click Heroes link in template'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> heroesLinkDe </span><span class="pun">=</span><span class="pln"> linkDes</span><span class="pun">[</span><span class="lit">1</span><span class="pun">];</span><span class="pln">   </span><span class="com">// heroes link </span><a href="api/core/DebugElement" class="code-anchor"><span class="com">DebugElement</span></a><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> heroesLink </span><span class="pun">=</span><span class="pln"> routerLinks</span><span class="pun">[</span><span class="lit">1</span><span class="pun">];</span><span class="pln"> </span><span class="com">// heroes link directive</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">heroesLink</span><span class="pun">.</span><span class="pln">navigatedTo</span><span class="pun">).</span><span class="pln">toBeNull</span><span class="pun">(</span><span class="str">'should not have </span><a href="api/router/Router#navigated" class="code-anchor"><span class="str">navigated</span></a><span class="str"> yet'</span><span class="pun">);</span><span class="pln">

  heroesLinkDe</span><span class="pun">.</span><span class="pln">triggerEventHandler</span><span class="pun">(</span><span class="str">'click'</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">);</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">heroesLink</span><span class="pun">.</span><span class="pln">navigatedTo</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'/heroes'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><div class="alert is-helpful"><p translation-result="on">其实<em>这个例子中</em>的“click”测试误入歧途了。 它测试的重点其实是 <code>RouterLinkDirectiveStub</code> ，而不是该组件。 这是写桩指令时常见的错误。</p><p translation-origin="off">The "click" test <em>in this example</em> is misleading. It tests the <code>RouterLinkDirectiveStub</code> rather than the <em>component</em>. This is a common failing of directive stubs.</p><p translation-result="on">在本章中，它有存在的必要。 它演示了如何在不涉及完整路由器机制的情况下，如何找到 <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> 元素、点击它并检查结果。 要测试更复杂的组件，你可能需要具备这样的能力，能改变视图和重新计算参数，或者当用户点击链接时，有能力重新安排导航选项。</p><p translation-origin="off">It has a legitimate purpose in this guide. It demonstrates how to find a <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> element, click it, and inspect a result, without engaging the full router machinery. This is a skill you may need to test a more sophisticated component, one that changes the display, re-calculates parameters, or re-arranges navigation options when the user clicks the link.</p></div><a id="why-stubbed-routerlink-tests"></a><h4 id="what-good-are-these-tests" translation-result="on">这些测试有什么优点？<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#what-good-are-these-tests"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="what-good-are-these-tests">What good are these tests?<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#what-good-are-these-tests"><i class="material-icons">link</i></a></h4><p translation-result="on">用 <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> 的桩指令进行测试可以确认带有链接和 outlet 的组件的设置的正确性，确认组件有应该有的链接，确认它们都指向了正确的方向。 这些测试程序不关心用户点击链接时，也不关心应用是否会成功的导航到目标组件。</p><p translation-origin="off">Stubbed <code><a href="api/router/RouterLink" class="code-anchor">RouterLink</a></code> tests can confirm that a component with links and an outlet is setup properly, that the component has the links it should have, and that they are all pointing in the expected direction. These tests do not concern whether the app will succeed in navigating to the target component when the user clicks a link.</p><p translation-result="on">对于这些有限的测试目标，使用 RouterLink 桩指令和 RouterOutlet 桩组件 是最佳选择。 依靠真正的路由器会让它们很脆弱。 它们可能因为与组件无关的原因而失败。 例如，一个导航守卫可能防止没有授权的用户访问 <code>HeroListComponent</code>。 这并不是 <code>AppComponent</code> 的过错，并且无论该组件怎么改变都无法修复这个失败的测试程序。</p><p translation-origin="off">Stubbing the RouterLink and RouterOutlet is the best option for such limited testing goals. Relying on the real router would make them brittle. They could fail for reasons unrelated to the component. For example, a navigation guard could prevent an unauthorized user from visiting the <code>HeroListComponent</code>. That's not the fault of the <code>AppComponent</code> and no change to that component could cure the failed test.</p><p translation-result="on">一组不同的测试程序可以探索当存在影响守卫的条件时（比如用户是否已认证和授权），该应用是否如期望般导航。</p><p translation-origin="off">A <em>different</em> battery of tests can explore whether the application navigates as expected in the presence of conditions that influence guards such as whether the user is authenticated and authorized.</p><div class="alert is-helpful"><p translation-result="on">未来对本章的更新将介绍如何使用 <code><a href="api/router/testing/RouterTestingModule" class="code-anchor">RouterTestingModule</a></code> 来编写这样的测试程序。</p><p translation-origin="off">A future guide update will explain how to write such tests with the <code><a href="api/router/testing/RouterTestingModule" class="code-anchor">RouterTestingModule</a></code>.</p></div><hr><a id="page-object"></a><h3 id="use-a-page-object" translation-result="on">使用页面（page）对象<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#use-a-page-object"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="use-a-page-object">Use a <em>page</em> object<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#use-a-page-object"><i class="material-icons">link</i></a></h3><p translation-result="on"><code>HeroDetailComponent</code> 是带有标题、两个英雄字段和两个按钮的简单视图。</p><p translation-origin="off">The <code>HeroDetailComponent</code> is a simple view with a title, two hero fields, and two buttons.</p><div class="lightbox"><img src="generated/images/guide/testing/hero-detail.component.png" alt="HeroDetailComponent in action" width="269" height="170"></div><p translation-result="on">但即使是这么简单的表单，其模板中也涉及到不少复杂性。</p><p translation-origin="off">But there's plenty of template complexity even in this simple form.</p><code-example path="testing/src/app/hero/hero-detail.component.html" header="app/hero/hero-detail.component.html" ng-version="9.0.0-rc.11"><div style="display:none">&lt;div *<a href="api/common/NgIf" class="code-anchor">ngIf</a>="hero"&gt; &lt;h2&gt;&lt;span&gt;{{hero.name | <a href="api/common/TitleCasePipe" class="code-anchor">titlecase</a>}}&lt;/span&gt; Details&lt;/h2&gt; &lt;div&gt; &lt;label&gt;id: &lt;/label&gt;{{hero.id}}&lt;/div&gt; &lt;div&gt; &lt;label for="name"&gt;name: &lt;/label&gt; &lt;input id="name" [(<a href="api/forms/NgModel" class="code-anchor">ngModel</a>)]="hero.name" placeholder="name" /&gt; &lt;/div&gt; &lt;button (click)="save()"&gt;Save&lt;/button&gt; &lt;button (click)="cancel()"&gt;Cancel&lt;/button&gt; &lt;/div&gt;</div><header class="ng-star-inserted">app/hero/hero-detail.component.html</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.html">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="tag">&lt;div</span><span class="pln"> *</span><a href="api/common/NgIf" class="code-anchor"><span class="atn">ngIf</span></a><span class="pun">=</span><span class="atv">"hero"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;h2&gt;&lt;span&gt;</span><span class="pln">{{hero.name | </span><a href="api/common/TitleCasePipe" class="code-anchor"><span class="pln">titlecase</span></a><span class="pln">}}</span><span class="tag">&lt;/span&gt;</span><span class="pln"> Details</span><span class="tag">&lt;/h2&gt;</span><span class="pln">
  </span><span class="tag">&lt;div&gt;</span><span class="pln">
    </span><span class="tag">&lt;label&gt;</span><span class="pln">id: </span><span class="tag">&lt;/label&gt;</span><span class="pln">{{hero.id}}</span><span class="tag">&lt;/div&gt;</span><span class="pln">
  </span><span class="tag">&lt;div&gt;</span><span class="pln">
    </span><span class="tag">&lt;label</span><span class="pln"> </span><span class="atn">for</span><span class="pun">=</span><span class="atv">"name"</span><span class="tag">&gt;</span><span class="pln">name: </span><span class="tag">&lt;/label&gt;</span><span class="pln">
    </span><span class="tag">&lt;input</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"name"</span><span class="pln"> [(</span><a href="api/forms/NgModel" class="code-anchor"><span class="atn">ngModel</span></a><span class="pln">)]</span><span class="pun">=</span><span class="atv">"hero.name"</span><span class="pln"> </span><span class="atn">placeholder</span><span class="pun">=</span><span class="atv">"name"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;/div&gt;</span><span class="pln">
  </span><span class="tag">&lt;button</span><span class="pln"> (</span><span class="atn">click</span><span class="pln">)</span><span class="pun">=</span><span class="atv">"save()"</span><span class="tag">&gt;</span><span class="pln">Save</span><span class="tag">&lt;/button&gt;</span><span class="pln">
  </span><span class="tag">&lt;button</span><span class="pln"> (</span><span class="atn">click</span><span class="pln">)</span><span class="pun">=</span><span class="atv">"cancel()"</span><span class="tag">&gt;</span><span class="pln">Cancel</span><span class="tag">&lt;/button&gt;</span><span class="pln">
</span><span class="tag">&lt;/div&gt;</span></code>
    </pre></aio-code></code-example><p translation-result="on">这些供练习用的组件需要 ……</p><p translation-origin="off">Tests that exercise the component need ...</p><ul><li><p translation-result="on">等获取到英雄之后才能让元素出现在 DOM 中。</p><p translation-origin="off">to wait until a hero arrives before elements appear in the DOM.</p></li><li><p translation-result="on">一个对标题文本的引用。</p><p translation-origin="off">a reference to the title text.</p></li><li><p translation-result="on">一个对 name 输入框的引用，以便对它进行探查和修改。</p><p translation-origin="off">a reference to the name input box to inspect and set it.</p></li><li><p translation-result="on">引用两个按钮，以便点击它们。</p><p translation-origin="off">references to the two buttons so they can click them.</p></li><li><p translation-result="on">为组件和路由器的方法安插间谍。</p><p translation-origin="off">spies for some of the component and router methods.</p></li></ul><p translation-result="on">即使是像这样一个很小的表单，也能产生令人疯狂的错综复杂的条件设置和 CSS 元素选择。</p><p translation-origin="off">Even a small form such as this one can produce a mess of tortured conditional setup and CSS element selection.</p><p translation-result="on">可以使用 <code>Page</code> 类来征服这种复杂性。<code>Page</code> 类可以处理对组件属性的访问，并对设置这些属性的逻辑进行封装。</p><p translation-origin="off">Tame the complexity with a <code>Page</code> class that handles access to component properties and encapsulates the logic that sets them.</p><p translation-result="on">下面是一个供 <code>hero-detail.component.spec.ts</code> 使用的 <code>Page</code> 类</p><p translation-origin="off">Here is such a <code>Page</code> class for the <code>hero-detail.component.spec.ts</code></p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="page" header="app/hero/hero-detail.component.spec.ts (Page)" ng-version="9.0.0-rc.11"><div style="display:none">class Page { // getter <a href="api/core/DebugElement#properties" class="code-anchor">properties</a> wait to <a href="api/animations/query" class="code-anchor">query</a> the DOM until called. get buttons() { return this.queryAll&lt;HTMLButtonElement&gt;('button'); } get saveBtn() { return this.buttons[0]; } get cancelBtn() { return this.buttons[1]; } get nameDisplay() { return this.query&lt;HTMLElement&gt;('span'); } get nameInput() { return this.query&lt;HTMLInputElement&gt;('input'); } gotoListSpy: jasmine.Spy; navigateSpy: jasmine.Spy; constructor(fixture: <a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a>&lt;HeroDetailComponent&gt;) { // get the navigate spy from the injected router spy object const routerSpy = &lt;any&gt; fixture.debugElement.injector.get(<a href="api/router/Router" class="code-anchor">Router</a>); this.navigateSpy = routerSpy.navigate; // spy on component's `gotoList()` method const component = fixture.componentInstance; this.gotoListSpy = spyOn(component, 'gotoList').and.callThrough(); } //// <a href="api/animations/query" class="code-anchor">query</a> helpers //// private <a href="api/animations/query" class="code-anchor">query</a>&lt;T&gt;(selector: string): T { return fixture.nativeElement.querySelector(selector); } private queryAll&lt;T&gt;(selector: string): T[] { return fixture.nativeElement.querySelectorAll(selector); } }</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (Page)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (Page)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">class</span><span class="pln"> </span><span class="typ">Page</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// getter </span><a href="api/core/DebugElement#properties" class="code-anchor"><span class="com">properties</span></a><span class="com"> wait to </span><a href="api/animations/query" class="code-anchor"><span class="com">query</span></a><span class="com"> the DOM until called.</span><span class="pln">
  </span><span class="kwd">get</span><span class="pln"> buttons</span><span class="pun">()</span><span class="pln">     </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">queryAll</span><span class="pun">&lt;</span><span class="typ">HTMLButtonElement</span><span class="pun">&gt;(</span><span class="str">'button'</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
  </span><span class="kwd">get</span><span class="pln"> saveBtn</span><span class="pun">()</span><span class="pln">     </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">buttons</span><span class="pun">[</span><span class="lit">0</span><span class="pun">];</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
  </span><span class="kwd">get</span><span class="pln"> cancelBtn</span><span class="pun">()</span><span class="pln">   </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">buttons</span><span class="pun">[</span><span class="lit">1</span><span class="pun">];</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
  </span><span class="kwd">get</span><span class="pln"> nameDisplay</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">query</span><span class="pun">&lt;</span><span class="typ">HTMLElement</span><span class="pun">&gt;(</span><span class="str">'span'</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
  </span><span class="kwd">get</span><span class="pln"> nameInput</span><span class="pun">()</span><span class="pln">   </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">query</span><span class="pun">&lt;</span><span class="typ">HTMLInputElement</span><span class="pun">&gt;(</span><span class="str">'input'</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln">

  gotoListSpy</span><span class="pun">:</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="typ">Spy</span><span class="pun">;</span><span class="pln">
  navigateSpy</span><span class="pun">:</span><span class="pln">  jasmine</span><span class="pun">.</span><span class="typ">Spy</span><span class="pun">;</span><span class="pln">

  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="pln">fixture</span><span class="pun">:</span><span class="pln"> </span><a href="api/core/testing/ComponentFixture" class="code-anchor"><span class="typ">ComponentFixture</span></a><span class="pun">&lt;</span><span class="typ">HeroDetailComponent</span><span class="pun">&gt;)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="com">// get the navigate spy from the injected router spy object</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> routerSpy </span><span class="pun">=</span><span class="pln"> </span><span class="str">&lt;any&gt;</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">.</span><span class="pln">injector</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><a href="api/router/Router" class="code-anchor"><span class="typ">Router</span></a><span class="pun">);</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">navigateSpy </span><span class="pun">=</span><span class="pln"> routerSpy</span><span class="pun">.</span><span class="pln">navigate</span><span class="pun">;</span><span class="pln">

    </span><span class="com">// spy on component's `gotoList()` method</span><span class="pln">
    </span><span class="kwd">const</span><span class="pln"> component </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">gotoListSpy </span><span class="pun">=</span><span class="pln"> spyOn</span><span class="pun">(</span><span class="pln">component</span><span class="pun">,</span><span class="pln"> </span><span class="str">'gotoList'</span><span class="pun">).</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">callThrough</span><span class="pun">();</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">

  </span><span class="com">//// </span><a href="api/animations/query" class="code-anchor"><span class="com">query</span></a><span class="com"> helpers ////</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> </span><a href="api/animations/query" class="code-anchor"><span class="pln">query</span></a><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;(</span><span class="pln">selector</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">):</span><span class="pln"> T </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="pln">selector</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">

  </span><span class="kwd">private</span><span class="pln"> queryAll</span><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;(</span><span class="pln">selector</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">):</span><span class="pln"> T</span><span class="pun">[]</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">querySelectorAll</span><span class="pun">(</span><span class="pln">selector</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">现在，用来操作和检查组件的重要钩子都被井然有序的组织起来了，可以通过 <code>page</code> 实例来使用它们。</p><p translation-origin="off">Now the important hooks for component manipulation and inspection are neatly organized and accessible from an instance of <code>Page</code>.</p><p translation-result="on"><code>createComponent</code> 方法会创建一个 <code>page</code> 对象，并在 <code>hero</code> 到来时自动填补空白。</p><p translation-origin="off">A <code>createComponent</code> method creates a <code>page</code> object and fills in the blanks once the <code>hero</code> arrives.</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="create-component" header="app/hero/hero-detail.component.spec.ts (createComponent)" ng-version="9.0.0-rc.11"><div style="display:none">/** Create the HeroDetailComponent, initialize it, set test variables */ function createComponent() { fixture = TestBed.createComponent(HeroDetailComponent); component = fixture.componentInstance; page = new Page(fixture); // 1st change detection triggers ngOnInit which gets a hero fixture.detectChanges(); return fixture.whenStable().then(() =&gt; { // 2nd change detection displays the async-fetched hero fixture.detectChanges(); }); }</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (createComponent)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (createComponent)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">/** Create the HeroDetailComponent, initialize it, set test variables  */</span><span class="pln">
</span><span class="kwd">function</span><span class="pln"> createComponent</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">HeroDetailComponent</span><span class="pun">);</span><span class="pln">
  component </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">
  page </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Page</span><span class="pun">(</span><span class="pln">fixture</span><span class="pun">);</span><span class="pln">

  </span><span class="com">// 1st change detection triggers ngOnInit which gets a hero</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">whenStable</span><span class="pun">().</span><span class="kwd">then</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="com">// 2nd change detection displays the async-fetched hero</span><span class="pln">
    fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">前面小节中的 <a href="guide/testing#tests-w-test-double"><code>HeroDetailComponent</code> 测试</a>示范了如何 <code>createComponent</code>，而 <code>page</code> 让这些测试保持简短而富有表达力。 而且还不用分心：不用等待承诺被解析，不必在 DOM 中找出元素的值才能进行比较。</p><p translation-origin="off">The <a href="guide/testing#tests-w-test-double"><em>HeroDetailComponent</em> tests</a> in an earlier section demonstrate how <code>createComponent</code> and <code>page</code> keep the tests short and <em>on message</em>. There are no distractions: no waiting for promises to resolve and no searching the DOM for element values to compare.</p><p translation-result="on">还有更多的 <code>HeroDetailComponent</code> 测试可以证明这一点。</p><p translation-origin="off">Here are a few more <code>HeroDetailComponent</code> tests to reinforce the point.</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="selected-tests" header="app/hero/hero-detail.component.spec.ts (selected tests)" ng-version="9.0.0-rc.11"><div style="display:none">it('should display that hero\'s name', () =&gt; { expect(page.nameDisplay.textContent).toBe(expectedHero.name); }); it('should navigate when click cancel', () =&gt; { click(page.cancelBtn); expect(page.navigateSpy.calls.any()).toBe(true, 'router.navigate called'); }); it('should save when click save but not navigate immediately', () =&gt; { // Get service injected into component and spy on its`saveHero` method. // It delegates to fake `HeroService.updateHero` which delivers a safe test result. const hds = fixture.debugElement.injector.get(HeroDetailService); const saveSpy = spyOn(hds, 'saveHero').and.callThrough(); click(page.saveBtn); expect(saveSpy.calls.any()).toBe(true, 'HeroDetailService.save called'); expect(page.navigateSpy.calls.any()).toBe(false, 'router.navigate not called'); }); it('should navigate when click save and save resolves', <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(() =&gt; { click(page.saveBtn); <a href="api/core/testing/tick" class="code-anchor">tick</a>(); // wait for <a href="api/core/testing/async" class="code-anchor">async</a> save to complete expect(page.navigateSpy.calls.any()).toBe(true, 'router.navigate called'); })); it('should convert hero name to <a href="api/platform-browser/Title" class="code-anchor">Title</a> Case', () =&gt; { // get the name's input and display elements from the DOM const hostElement = fixture.nativeElement; const nameInput: HTMLInputElement = hostElement.querySelector('input'); const nameDisplay: HTMLElement = hostElement.querySelector('span'); // simulate user entering a new name into the input box nameInput.value = 'quick BROWN fOx'; // dispatch a DOM event so that Angular learns of input value change. // use newEvent utility function (not provided by Angular) for better <a href="api/animations/browser" class="code-anchor">browser</a> compatibility nameInput.dispatchEvent(newEvent('input')); // Tell Angular to <a href="api/forms/NgModel#update" class="code-anchor">update</a> the display binding through the title pipe fixture.detectChanges(); expect(nameDisplay.textContent).toBe('Quick Brown Fox'); });</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (selected tests)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (selected tests)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should display that hero\'s name'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">nameDisplay</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">expectedHero</span><span class="pun">.</span><span class="pln">name</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should navigate when click cancel'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  click</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">cancelBtn</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">navigateSpy</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">any</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">,</span><span class="pln"> </span><span class="str">'router.navigate called'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should save when click save but not navigate immediately'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// Get service injected into component and spy on its`saveHero` method.</span><span class="pln">
  </span><span class="com">// It delegates to fake `HeroService.updateHero` which delivers a safe test result.</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> hds </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">.</span><span class="pln">injector</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><span class="typ">HeroDetailService</span><span class="pun">);</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> saveSpy </span><span class="pun">=</span><span class="pln"> spyOn</span><span class="pun">(</span><span class="pln">hds</span><span class="pun">,</span><span class="pln"> </span><span class="str">'saveHero'</span><span class="pun">).</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">callThrough</span><span class="pun">();</span><span class="pln">

  click</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">saveBtn</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">saveSpy</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">any</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">,</span><span class="pln"> </span><span class="str">'HeroDetailService.save called'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">navigateSpy</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">any</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">false</span><span class="pun">,</span><span class="pln"> </span><span class="str">'router.navigate not called'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should navigate when click save and save resolves'</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  click</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">saveBtn</span><span class="pun">);</span><span class="pln">
  </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">();</span><span class="pln"> </span><span class="com">// wait for </span><a href="api/core/testing/async" class="code-anchor"><span class="com">async</span></a><span class="com"> save to complete</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">navigateSpy</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">any</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">,</span><span class="pln"> </span><span class="str">'router.navigate called'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}));</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should convert hero name to </span><a href="api/platform-browser/Title" class="code-anchor"><span class="str">Title</span></a><span class="str"> Case'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// get the name's input and display elements from the DOM</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> hostElement </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> nameInput</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLInputElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> hostElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'input'</span><span class="pun">);</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> nameDisplay</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> hostElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'span'</span><span class="pun">);</span><span class="pln">

  </span><span class="com">// simulate user entering a new name into the input box</span><span class="pln">
  nameInput</span><span class="pun">.</span><span class="kwd">value</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="str">'quick BROWN  fOx'</span><span class="pun">;</span><span class="pln">

  </span><span class="com">// dispatch a DOM event so that Angular learns of input value change.</span><span class="pln">
  </span><span class="com">// use newEvent utility function (not provided by Angular) for better </span><a href="api/animations/browser" class="code-anchor"><span class="com">browser</span></a><span class="com"> compatibility</span><span class="pln">
  nameInput</span><span class="pun">.</span><span class="pln">dispatchEvent</span><span class="pun">(</span><span class="pln">newEvent</span><span class="pun">(</span><span class="str">'input'</span><span class="pun">));</span><span class="pln">

  </span><span class="com">// Tell Angular to </span><a href="api/forms/NgModel#update" class="code-anchor"><span class="com">update</span></a><span class="com"> the display binding through the title pipe</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">nameDisplay</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'Quick Brown  Fox'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><hr><a id="compile-components"></a><h3 id="calling-compilecomponents" translation-result="on">调用 <code>compileComponents()</code><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#calling-compilecomponents"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="calling-compilecomponents">Calling <em>compileComponents()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#calling-compilecomponents"><i class="material-icons">link</i></a></h3><div class="alert is-helpful"><p translation-result="on">如果你<em>只想</em>使用 CLI 的 <code>ng test</code> 命令来运行测试，那么可以忽略这一节。</p><p translation-origin="off">You can ignore this section if you <em>only</em> run tests with the CLI <code>ng test</code> command because the CLI compiles the application before running the tests.</p></div><p translation-result="on">如果你在<strong>非 CLI 环境</strong>中运行测试，这些测试可能会报错，错误信息如下：</p><p translation-origin="off">If you run tests in a <strong>non-CLI environment</strong>, the tests may fail with a message like this one:</p><code-example language="sh" class="code-shell" hidecopy="" ng-version="9.0.0-rc.11"><div style="display:none">Error: This test module uses the component BannerComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test.</div><aio-code><pre class="lang-sh prettyprint">      
      <code class="animated fadeIn"><span class="typ">Error</span><span class="pun">:</span><span class="pln"> </span><span class="typ">This</span><span class="pln"> test module uses the component </span><span class="typ">BannerComponent</span><span class="pln">
which is using a </span><span class="str">"templateUrl"</span><span class="pln"> or </span><span class="str">"styleUrls"</span><span class="pun">,</span><span class="pln"> but they were never compiled</span><span class="pun">.</span><span class="pln">
</span><span class="typ">Please</span><span class="pln"> call </span><span class="str">"TestBed.compileComponents"</span><span class="pln"> before your test</span><span class="pun">.</span></code>
    </pre></aio-code></code-example><p translation-result="on">问题的根源在于这个测试中至少有一个组件引用了外部模板或外部 CSS 文件，就像下面这个版本的 <code>BannerComponent</code> 所示：</p><p translation-origin="off">The root of the problem is at least one of the components involved in the test specifies an external template or CSS file as the following version of the <code>BannerComponent</code> does.</p><code-example path="testing/src/app/banner/banner-external.component.ts" header="app/banner/banner-external.component.ts (external template &amp; css)" ng-version="9.0.0-rc.11"><div style="display:none">import { <a href="api/core/Component" class="code-anchor">Component</a> } from '@angular/core'; @<a href="api/core/Component" class="code-anchor">Component</a>({ selector: 'app-banner', <a href="api/core/Component#templateUrl" class="code-anchor">templateUrl</a>: './banner-external.component.html', <a href="api/core/Component#styleUrls" class="code-anchor">styleUrls</a>: ['./banner-external.component.css'] }) export class BannerComponent { title = 'Test Tour of Heroes'; }</div><header class="ng-star-inserted">app/banner/banner-external.component.ts (external template &amp; css)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner-external.component.ts (external template &amp; css)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/Component" class="code-anchor"><span class="typ">Component</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core'</span><span class="pun">;</span><span class="pln">

</span><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">
  selector</span><span class="pun">:</span><span class="pln"> </span><span class="str">'app-banner'</span><span class="pun">,</span><span class="pln">
  </span><a href="api/core/Component#templateUrl" class="code-anchor"><span class="pln">templateUrl</span></a><span class="pun">:</span><span class="pln"> </span><span class="str">'./banner-external.component.html'</span><span class="pun">,</span><span class="pln">
  </span><a href="api/core/Component#styleUrls" class="code-anchor"><span class="pln">styleUrls</span></a><span class="pun">:</span><span class="pln">  </span><span class="pun">[</span><span class="str">'./banner-external.component.css'</span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  title </span><span class="pun">=</span><span class="pln"> </span><span class="str">'Test Tour of Heroes'</span><span class="pun">;</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">当 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 视图创建组件时，这个测试失败了：</p><p translation-origin="off">The test fails when the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> tries to create the component.</p><code-example path="testing/src/app/banner/banner.component.spec.ts" region="configure-and-create" header="app/banner/banner.component.spec.ts (setup that fails)" avoid="" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(() =&gt; { TestBed.configureTestingModule({ declarations: [ BannerComponent ], }); fixture = TestBed.createComponent(BannerComponent); });</div><header class="ng-star-inserted">app/banner/banner.component.spec.ts (setup that fails)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner.component.spec.ts (setup that fails)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
  fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">BannerComponent</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">回想一下，这个应用从未编译过。 所以当你调用 <code>createComponent()</code> 的时候，<code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 就会进行隐式编译。</p><p translation-origin="off">Recall that the app hasn't been compiled. So when you call <code>createComponent()</code>, the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> compiles implicitly.</p><p translation-result="on">当它的源码都在内存中的时候，这样做没问题。 不过 <code>BannerComponent</code> 需要一些外部文件，编译时必须从文件系统中读取它，而这是一个天生的<em>异步</em>操作。</p><p translation-origin="off">That's not a problem when the source code is in memory. But the <code>BannerComponent</code> requires external files that the compiler must read from the file system, an inherently <em>asynchronous</em> operation.</p><p translation-result="on">如果 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 继续执行，这些测试就会继续运行，并在编译器完成这些异步工作之前导致莫名其妙的失败。</p><p translation-origin="off">If the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> were allowed to continue, the tests would run and fail mysteriously before the compiler could finished.</p><p translation-result="on">这些错误信息告诉你要使用 <code>compileComponents()</code> 进行显式的编译。</p><p translation-origin="off">The preemptive error message tells you to compile explicitly with <code>compileComponents()</code>.</p><h4 id="compilecomponents-is-async" translation-result="on"><code>compileComponents()</code> 是异步的<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#compilecomponents-is-async"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="compilecomponents-is-async"><em>compileComponents()</em> is async<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#compilecomponents-is-async"><i class="material-icons">link</i></a></h4><p translation-result="on">你必须在异步测试函数中调用 <code>compileComponents()</code>。</p><p translation-origin="off">You must call <code>compileComponents()</code> within an asynchronous test function.</p><div class="alert is-critical"><p translation-result="on">如果你忘了把测试函数标为异步的（比如忘了像稍后的代码中那样使用 <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code>），就会看到下列错误。</p><p translation-origin="off">If you neglect to make the test function async (e.g., forget to use <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> as described below), you'll see this error message</p><code-example language="sh" class="code-shell" hidecopy="" ng-version="9.0.0-rc.11"><div style="display:none">Error: ViewDestroyedError: Attempt to use a destroyed view</div><aio-code><pre class="lang-sh prettyprint">      
      <code class="animated fadeIn"><span class="typ">Error</span><span class="pun">:</span><span class="pln"> </span><span class="typ">ViewDestroyedError</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Attempt</span><span class="pln"> to use a destroyed view</span></code>
    </pre></aio-code></code-example></div><p translation-result="on">典型的做法是把准备逻辑拆成两个独立的 <code>beforeEach()</code> 函数：</p><p translation-origin="off">A typical approach is to divide the setup logic into two separate <code>beforeEach()</code> functions:</p><ol><li><p translation-result="on">异步的 <code>beforeEach()</code> 负责编译组件</p><p translation-origin="off">An async <code>beforeEach()</code> that compiles the components</p></li><li><p translation-result="on">同步的 <code>beforeEach()</code> 负责执行其余的准备代码。</p><p translation-origin="off">A synchronous <code>beforeEach()</code> that performs the remaining setup.</p></li></ol><p translation-result="on">要想使用这种模式，就要和其它符号一起从测试库中导入 <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 辅助函数。</p><p translation-origin="off">To follow this pattern, import the <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> helper with the other testing symbols.</p><code-example path="testing/src/app/banner/banner-external.component.spec.ts" region="import-async" ng-version="9.0.0-rc.11"><div style="display:none">import { <a href="api/core/testing/async" class="code-anchor">async</a>, <a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a>, <a href="api/core/testing/TestBed" class="code-anchor">TestBed</a> } from '@angular/core/testing';</div><aio-code><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/ComponentFixture" class="code-anchor"><span class="typ">ComponentFixture</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/TestBed" class="code-anchor"><span class="typ">TestBed</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core/testing'</span><span class="pun">;</span></code>
    </pre></aio-code></code-example><h4 id="the-async-beforeeach" translation-result="on">异步的 <code>beforeEach</code><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-async-beforeeach"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="the-async-beforeeach">The async <em>beforeEach</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-async-beforeeach"><i class="material-icons">link</i></a></h4><p translation-result="on">像下面这样编写第一个异步的 <code>beforeEach</code>。</p><p translation-origin="off">Write the first async <code>beforeEach</code> like this.</p><code-example path="testing/src/app/banner/banner-external.component.spec.ts" region="async-before-each" header="app/banner/banner-external.component.spec.ts (async beforeEach)" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { TestBed.configureTestingModule({ declarations: [ BannerComponent ], }) .compileComponents(); // compile template and css }));</div><header class="ng-star-inserted">app/banner/banner-external.component.spec.ts (async beforeEach)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner-external.component.spec.ts (async beforeEach)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
  </span><span class="pun">})</span><span class="pln">
  </span><span class="pun">.</span><span class="pln">compileComponents</span><span class="pun">();</span><span class="pln">  </span><span class="com">// compile template and css</span><span class="pln">
</span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> 辅助函数接受一个无参函数，其内容是环境准备代码。</p><p translation-origin="off">The <code><a href="api/core/testing/async" class="code-anchor">async</a>()</code> helper function takes a parameterless function with the body of the setup.</p><p translation-result="on"><code>TestBed.configureTestingModule()</code> 方法返回 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 类，所以你可以链式调用其它 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 中的静态方法，比如 <code>compileComponents()</code>。</p><p translation-origin="off">The <code>TestBed.configureTestingModule()</code> method returns the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> class so you can chain calls to other <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> static methods such as <code>compileComponents()</code>.</p><p translation-result="on">在这个例子中，<code>BannerComponent</code> 是仅有的待编译组件。 其它例子中可能会使用多个组件来配置测试模块，并且可能引入某些具有其它组件的应用模块。 它们中的任何一个都可能需要外部文件。</p><p translation-origin="off">In this example, the <code>BannerComponent</code> is the only component to compile. Other examples configure the testing module with multiple components and may import application modules that hold yet more components. Any of them could be require external files.</p><p translation-result="on"><code>TestBed.compileComponents</code> 方法会异步编译测试模块中配置过的所有组件。</p><p translation-origin="off">The <code>TestBed.compileComponents</code> method asynchronously compiles all components configured in the testing module.</p><div class="alert is-important"><p translation-result="on">在调用了 <code>compileComponents()</code> 之后就不能再重新配置 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 了。</p><p translation-origin="off">Do not re-configure the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> after calling <code>compileComponents()</code>.</p></div><p translation-result="on">调用 <code>compileComponents()</code> 会关闭当前的 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 实例，不再允许进行配置。 你不能再调用任何 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 中的配置方法，既不能调 <code>configureTestingModule()</code>，也不能调用任何 <code>override...</code> 方法。如果你试图这么做，<code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 就会抛出错误。</p><p translation-origin="off">Calling <code>compileComponents()</code> closes the current <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> instance to further configuration. You cannot call any more <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> configuration methods, not <code>configureTestingModule()</code> nor any of the <code>override...</code> methods. The <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> throws an error if you try.</p><p translation-result="on">确保 <code>compileComponents()</code> 是调用 <code>TestBed.createComponent()</code> 之前的最后一步。</p><p translation-origin="off">Make <code>compileComponents()</code> the last step before calling <code>TestBed.createComponent()</code>.</p><h4 id="the-synchronous-beforeeach" translation-result="on">同步的 <code>beforeEach</code><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-synchronous-beforeeach"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="the-synchronous-beforeeach">The synchronous <em>beforeEach</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-synchronous-beforeeach"><i class="material-icons">link</i></a></h4><p translation-result="on">第二个同步 <code>beforeEach()</code> 的例子包含剩下的准备步骤， 包括创建组件和查询那些要检查的元素。</p><p translation-origin="off">The second, synchronous <code>beforeEach()</code> contains the remaining setup steps, which include creating the component and querying for elements to inspect.</p><code-example path="testing/src/app/banner/banner-external.component.spec.ts" region="sync-before-each" header="app/banner/banner-external.component.spec.ts (synchronous beforeEach)" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(() =&gt; { fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; // BannerComponent test instance h1 = fixture.nativeElement.querySelector('h1'); });</div><header class="ng-star-inserted">app/banner/banner-external.component.spec.ts (synchronous beforeEach)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner-external.component.spec.ts (synchronous beforeEach)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">BannerComponent</span><span class="pun">);</span><span class="pln">
  component </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln"> </span><span class="com">// BannerComponent test instance</span><span class="pln">
  h1 </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'h1'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">测试运行器（runner）会先等待第一个异步 <code>beforeEach</code> 函数执行完再调用第二个。</p><p translation-origin="off">You can count on the test runner to wait for the first asynchronous <code>beforeEach</code> to finish before calling the second.</p><h4 id="consolidated-setup" translation-result="on">整理过的准备代码<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#consolidated-setup"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="consolidated-setup">Consolidated setup<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#consolidated-setup"><i class="material-icons">link</i></a></h4><p translation-result="on">你可以把这两个 <code>beforeEach()</code> 函数重整成一个异步的 <code>beforeEach()</code>。</p><p translation-origin="off">You can consolidate the two <code>beforeEach()</code> functions into a single, async <code>beforeEach()</code>.</p><p translation-result="on"><code>compileComponents()</code> 方法返回一个承诺，所以你可以通过把同步代码移到 <code>then(...)</code> 回调中， 以便在编译完成<em>之后</em> 执行那些同步准备任务。</p><p translation-origin="off">The <code>compileComponents()</code> method returns a promise so you can perform the synchronous setup tasks <em>after</em> compilation by moving the synchronous code into a <code>then(...)</code> callback.</p><code-example path="testing/src/app/banner/banner-external.component.spec.ts" region="one-before-each" header="app/banner/banner-external.component.spec.ts (one beforeEach)" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { TestBed.configureTestingModule({ declarations: [ BannerComponent ], }) .compileComponents() .then(() =&gt; { fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; h1 = fixture.nativeElement.querySelector('h1'); }); }));</div><header class="ng-star-inserted">app/banner/banner-external.component.spec.ts (one beforeEach)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/banner/banner-external.component.spec.ts (one beforeEach)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">BannerComponent</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
  </span><span class="pun">})</span><span class="pln">
  </span><span class="pun">.</span><span class="pln">compileComponents</span><span class="pun">()</span><span class="pln">
  </span><span class="pun">.</span><span class="kwd">then</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">BannerComponent</span><span class="pun">);</span><span class="pln">
    component </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">componentInstance</span><span class="pun">;</span><span class="pln">
    h1 </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'h1'</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
</span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><h4 id="compilecomponents-is-harmless" translation-result="on"><code>compileComponents()</code> 是无害的<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#compilecomponents-is-harmless"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="compilecomponents-is-harmless"><em>compileComponents()</em> is harmless<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#compilecomponents-is-harmless"><i class="material-icons">link</i></a></h4><p translation-result="on">在不需要 <code>compileComponents()</code> 的时候调用它也不会有害处。</p><p translation-origin="off">There's no harm in calling <code>compileComponents()</code> when it's not required.</p><p translation-result="on">虽然在运行 <code>ng test</code> 时永远都不需要调用 <code>compileComponents()</code>，但 CLI 生成的组件测试文件还是会调用它。</p><p translation-origin="off">The component test file generated by the CLI calls <code>compileComponents()</code> even though it is never required when running <code>ng test</code>.</p><p translation-result="on">但这篇指南中的这些测试只会在必要时才调用 <code>compileComponents</code>。</p><p translation-origin="off">The tests in this guide only call <code>compileComponents</code> when necessary.</p><hr><a id="import-module"></a><h3 id="setup-with-module-imports" translation-result="on">准备模块的 <code>imports</code><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#setup-with-module-imports"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="setup-with-module-imports">Setup with module imports<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#setup-with-module-imports"><i class="material-icons">link</i></a></h3><p translation-result="on">此前的组件测试程序使用了一些 <code>declarations</code> 来配置模块，就像这样：</p><p translation-origin="off">Earlier component tests configured the testing module with a few <code>declarations</code> like this:</p><code-example path="testing/src/app/dashboard/dashboard-hero.component.spec.ts" region="config-testbed" header="app/dashboard/dashboard-hero.component.spec.ts (configure TestBed)" ng-version="9.0.0-rc.11"><div style="display:none">TestBed.configureTestingModule({ declarations: [ DashboardHeroComponent ] })</div><header class="ng-star-inserted">app/dashboard/dashboard-hero.component.spec.ts (configure TestBed)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/dashboard/dashboard-hero.component.spec.ts (configure TestBed)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
  declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">DashboardHeroComponent</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>DashbaordComponent</code> 非常简单。它不需要帮助。 但是更加复杂的组件通常依赖其它组件、指令、管道和提供商， 所以这些必须也被添加到测试模块中。</p><p translation-origin="off">The <code>DashboardComponent</code> is simple. It needs no help. But more complex components often depend on other components, directives, pipes, and providers and these must be added to the testing module too.</p><p translation-result="on">幸运的是，<code>TestBed.configureTestingModule</code> 参数与传入 <code>@<a href="api/core/NgModule" class="code-anchor">NgModule</a></code> 装饰器的元数据一样，也就是所你也可以指定 <code>providers</code> 和 <code>imports</code>.</p><p translation-origin="off">Fortunately, the <code>TestBed.configureTestingModule</code> parameter parallels the metadata passed to the <code>@<a href="api/core/NgModule" class="code-anchor">NgModule</a></code> decorator which means you can also specify <code>providers</code> and <code>imports</code>.</p><p translation-result="on">虽然 <code>HeroDetailComponent</code> 很小，结构也很简单，但是它需要很多帮助。 除了从默认测试模块 <code><a href="api/common/CommonModule" class="code-anchor">CommonModule</a></code> 中获得的支持，它还需要：</p><p translation-origin="off">The <code>HeroDetailComponent</code> requires a lot of help despite its small size and simple construction. In addition to the support it receives from the default testing module <code><a href="api/common/CommonModule" class="code-anchor">CommonModule</a></code>, it needs:</p><ul><li><p translation-result="on"> <code><a href="api/forms/FormsModule" class="code-anchor">FormsModule</a></code> 里的 <code><a href="api/forms/NgModel" class="code-anchor">NgModel</a></code> 和其它，来进行双向数据绑定</p><p translation-origin="off"><code><a href="api/forms/NgModel" class="code-anchor">NgModel</a></code> and friends in the <code><a href="api/forms/FormsModule" class="code-anchor">FormsModule</a></code> to enable two-way data binding.</p></li><li><p translation-result="on"> <code>shared</code> 目录里的 <code><a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a></code></p><p translation-origin="off">The <code><a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a></code> from the <code>shared</code> folder.</p></li><li><p translation-result="on">一些路由器服务（测试程序将 stub 伪造它们）</p><p translation-origin="off">Router services (which these tests are stubbing).</p></li><li><p translation-result="on">英雄数据访问服务（同样被 stub 伪造了）</p><p translation-origin="off">Hero data access services (also stubbed).</p></li></ul><p translation-result="on">一种方法是从各个部分配置测试模块，就像这样：</p><p translation-origin="off">One approach is to configure the testing module from the individual pieces as in this example:</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="setup-forms-module" header="app/hero/hero-detail.component.spec.ts (FormsModule setup)" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { const routerSpy = createRouterSpy(); TestBed.configureTestingModule({ imports: [ <a href="api/forms/FormsModule" class="code-anchor">FormsModule</a> ], declarations: [ HeroDetailComponent, <a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a> ], providers: [ { provide: <a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a>, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: <a href="api/router/RouterOutlet#activatedRoute" class="code-anchor">activatedRoute</a> }, { provide: HeroService, useClass: TestHeroService }, { provide: <a href="api/router/Router" class="code-anchor">Router</a>, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: routerSpy}, ] }) .compileComponents(); }));</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (FormsModule setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (FormsModule setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> routerSpy </span><span class="pun">=</span><span class="pln"> createRouterSpy</span><span class="pun">();</span><span class="pln">

  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    imports</span><span class="pun">:</span><span class="pln">      </span><span class="pun">[</span><span class="pln"> </span><a href="api/forms/FormsModule" class="code-anchor"><span class="typ">FormsModule</span></a><span class="pln"> </span><span class="pun">],</span><span class="pln">
    declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">HeroDetailComponent</span><span class="pun">,</span><span class="pln"> </span><a href="api/common/TitleCasePipe" class="code-anchor"><span class="typ">TitleCasePipe</span></a><span class="pln"> </span><span class="pun">],</span><span class="pln">
    providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/ActivatedRoute" class="code-anchor"><span class="typ">ActivatedRoute</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> </span><a href="api/router/RouterOutlet#activatedRoute" class="code-anchor"><span class="pln">activatedRoute</span></a><span class="pln"> </span><span class="pun">},</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroService</span><span class="pun">,</span><span class="pln">    useClass</span><span class="pun">:</span><span class="pln"> </span><span class="typ">TestHeroService</span><span class="pln"> </span><span class="pun">},</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/Router" class="code-anchor"><span class="typ">Router</span></a><span class="pun">,</span><span class="pln">         </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> routerSpy</span><span class="pun">},</span><span class="pln">
    </span><span class="pun">]</span><span class="pln">
  </span><span class="pun">})</span><span class="pln">
  </span><span class="pun">.</span><span class="pln">compileComponents</span><span class="pun">();</span><span class="pln">
</span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><div class="alert is-helpful"><p translation-result="on">注意，<code>beforeEach()</code> 是异步的，它调用 <code>TestBed.compileComponents</code> 是因为 <code>HeroDetailComponent</code> 有外部模板和 CSS 文件。</p><p translation-origin="off">Notice that the <code>beforeEach()</code> is asynchronous and calls <code>TestBed.compileComponents</code> because the <code>HeroDetailComponent</code> has an external template and css file.</p><p translation-result="on">如前面的<a href="guide/testing#compile-components">调用 <code>compileComponents()</code></a>中所解释的那样，这些测试可以运行在非 CLI 环境下，那里 Angular 并不会在浏览器中编译它们。</p><p translation-origin="off">As explained in <a href="guide/testing#compile-components"><em>Calling compileComponents()</em></a> above, these tests could be run in a non-CLI environment where Angular would have to compile them in the browser.</p></div><h4 id="import-a-shared-module" translation-result="on">导入共享模块<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#import-a-shared-module"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="import-a-shared-module">Import a shared module<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#import-a-shared-module"><i class="material-icons">link</i></a></h4><p translation-result="on">因为很多应用组件都需要 <code><a href="api/forms/FormsModule" class="code-anchor">FormsModule</a></code> 和 <code><a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a></code>，所以开发者创建了 <code>SharedModule</code> 来把它们及其它常用的部分组合在一起。</p><p translation-origin="off">Because many app components need the <code><a href="api/forms/FormsModule" class="code-anchor">FormsModule</a></code> and the <code><a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a></code>, the developer created a <code>SharedModule</code> to combine these and other frequently requested parts.</p><p translation-result="on">这些测试配置也可以使用 <code>SharedModule</code>，如下所示：</p><p translation-origin="off">The test configuration can use the <code>SharedModule</code> too as seen in this alternative setup:</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="setup-shared-module" header="app/hero/hero-detail.component.spec.ts (SharedModule setup)" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { const routerSpy = createRouterSpy(); TestBed.configureTestingModule({ imports: [ SharedModule ], declarations: [ HeroDetailComponent ], providers: [ { provide: <a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a>, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: <a href="api/router/RouterOutlet#activatedRoute" class="code-anchor">activatedRoute</a> }, { provide: HeroService, useClass: TestHeroService }, { provide: <a href="api/router/Router" class="code-anchor">Router</a>, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: routerSpy}, ] }) .compileComponents(); }));</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (SharedModule setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (SharedModule setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> routerSpy </span><span class="pun">=</span><span class="pln"> createRouterSpy</span><span class="pun">();</span><span class="pln">

  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    imports</span><span class="pun">:</span><span class="pln">      </span><span class="pun">[</span><span class="pln"> </span><span class="typ">SharedModule</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
    declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">HeroDetailComponent</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
    providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/ActivatedRoute" class="code-anchor"><span class="typ">ActivatedRoute</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> </span><a href="api/router/RouterOutlet#activatedRoute" class="code-anchor"><span class="pln">activatedRoute</span></a><span class="pln"> </span><span class="pun">},</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroService</span><span class="pun">,</span><span class="pln">    useClass</span><span class="pun">:</span><span class="pln"> </span><span class="typ">TestHeroService</span><span class="pln"> </span><span class="pun">},</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/Router" class="code-anchor"><span class="typ">Router</span></a><span class="pun">,</span><span class="pln">         </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> routerSpy</span><span class="pun">},</span><span class="pln">
    </span><span class="pun">]</span><span class="pln">
  </span><span class="pun">})</span><span class="pln">
  </span><span class="pun">.</span><span class="pln">compileComponents</span><span class="pun">();</span><span class="pln">
</span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><p translation-result="on">它的导入声明少一些（未显示），稍微干净一些，小一些。</p><p translation-origin="off">It's a bit tighter and smaller, with fewer import statements (not shown).</p><a id="feature-module-import"></a><h4 id="import-a-feature-module" translation-result="on">导入特性模块<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#import-a-feature-module"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="import-a-feature-module">Import a feature module<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#import-a-feature-module"><i class="material-icons">link</i></a></h4><p translation-result="on"><code>HeroDetailComponent</code> 是 <code>HeroModule</code> 这个<a href="guide/feature-modules">特性模块</a>的一部分，它聚合了更多相互依赖的片段，包括 <code>SharedModule</code>。 试试下面这个导入了 <code>HeroModule</code> 的测试配置：</p><p translation-origin="off">The <code>HeroDetailComponent</code> is part of the <code>HeroModule</code> <a href="guide/feature-modules">Feature Module</a> that aggregates more of the interdependent pieces including the <code>SharedModule</code>. Try a test configuration that imports the <code>HeroModule</code> like this one:</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="setup-hero-module" header="app/hero/hero-detail.component.spec.ts (HeroModule setup)" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { const routerSpy = createRouterSpy(); TestBed.configureTestingModule({ imports: [ HeroModule ], providers: [ { provide: <a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a>, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: <a href="api/router/RouterOutlet#activatedRoute" class="code-anchor">activatedRoute</a> }, { provide: HeroService, useClass: TestHeroService }, { provide: <a href="api/router/Router" class="code-anchor">Router</a>, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: routerSpy}, ] }) .compileComponents(); }));</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (HeroModule setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (HeroModule setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> routerSpy </span><span class="pun">=</span><span class="pln"> createRouterSpy</span><span class="pun">();</span><span class="pln">

  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    imports</span><span class="pun">:</span><span class="pln">   </span><span class="pun">[</span><span class="pln"> </span><span class="typ">HeroModule</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
    providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/ActivatedRoute" class="code-anchor"><span class="typ">ActivatedRoute</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> </span><a href="api/router/RouterOutlet#activatedRoute" class="code-anchor"><span class="pln">activatedRoute</span></a><span class="pln"> </span><span class="pun">},</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroService</span><span class="pun">,</span><span class="pln">    useClass</span><span class="pun">:</span><span class="pln"> </span><span class="typ">TestHeroService</span><span class="pln"> </span><span class="pun">},</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/Router" class="code-anchor"><span class="typ">Router</span></a><span class="pun">,</span><span class="pln">         </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> routerSpy</span><span class="pun">},</span><span class="pln">
    </span><span class="pun">]</span><span class="pln">
  </span><span class="pun">})</span><span class="pln">
  </span><span class="pun">.</span><span class="pln">compileComponents</span><span class="pun">();</span><span class="pln">
</span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><p translation-result="on">这样特别清爽。只有 <code>providers</code> 里面的测试替身被保留。连 <code>HeroDetailComponent</code> 声明都消失了。</p><p translation-origin="off">That's <em>really</em> crisp. Only the <em>test doubles</em> in the <code>providers</code> remain. Even the <code>HeroDetailComponent</code> declaration is gone.</p><p translation-result="on">事实上，如果你试图声明它，Angular 就会抛出一个错误，因为 <code>HeroDetailComponent</code> 同时声明在了 <code>HeroModule</code> 和 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 创建的 <code>DynamicTestModule</code> 中。</p><p translation-origin="off">In fact, if you try to declare it, Angular will throw an error because <code>HeroDetailComponent</code> is declared in both the <code>HeroModule</code> and the <code>DynamicTestModule</code> created by the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>.</p><div class="alert is-helpful"><p translation-result="on">如果模块中有很多共同依赖，并且该模块很小（这也是特性模块的应有形态），那么直接导入组件的特性模块可以成为配置这些测试的简易方式。</p><p translation-origin="off">Importing the component's feature module can be the easiest way to configure tests when there are many mutual dependencies within the module and the module is small, as feature modules tend to be.</p></div><hr><a id="component-override"></a><h3 id="override-component-providers" translation-result="on">改写组件的服务提供商<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#override-component-providers"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="override-component-providers">Override component providers<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#override-component-providers"><i class="material-icons">link</i></a></h3><p translation-result="on"><code>HeroDetailComponent</code> 提供自己的 <code>HeroDetailService</code> 服务。</p><p translation-origin="off">The <code>HeroDetailComponent</code> provides its own <code>HeroDetailService</code>.</p><code-example path="testing/src/app/hero/hero-detail.component.ts" region="prototype" header="app/hero/hero-detail.component.ts (prototype)" ng-version="9.0.0-rc.11"><div style="display:none">@<a href="api/core/Component" class="code-anchor">Component</a>({ selector: 'app-hero-detail', <a href="api/core/Component#templateUrl" class="code-anchor">templateUrl</a>: './hero-detail.component.html', <a href="api/core/Component#styleUrls" class="code-anchor">styleUrls</a>: ['./hero-detail.component.css' ], providers: [ HeroDetailService ] }) export class HeroDetailComponent implements <a href="api/core/OnInit" class="code-anchor">OnInit</a> { constructor( private heroDetailService: HeroDetailService, private route: <a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a>, private router: <a href="api/router/Router" class="code-anchor">Router</a>) { } }</div><header class="ng-star-inserted">app/hero/hero-detail.component.ts (prototype)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.ts (prototype)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">
  selector</span><span class="pun">:</span><span class="pln">    </span><span class="str">'app-hero-detail'</span><span class="pun">,</span><span class="pln">
  </span><a href="api/core/Component#templateUrl" class="code-anchor"><span class="pln">templateUrl</span></a><span class="pun">:</span><span class="pln"> </span><span class="str">'./hero-detail.component.html'</span><span class="pun">,</span><span class="pln">
  </span><a href="api/core/Component#styleUrls" class="code-anchor"><span class="pln">styleUrls</span></a><span class="pun">:</span><span class="pln">  </span><span class="pun">[</span><span class="str">'./hero-detail.component.css'</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
  providers</span><span class="pun">:</span><span class="pln">  </span><span class="pun">[</span><span class="pln"> </span><span class="typ">HeroDetailService</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">HeroDetailComponent</span><span class="pln"> </span><span class="kwd">implements</span><span class="pln"> </span><a href="api/core/OnInit" class="code-anchor"><span class="typ">OnInit</span></a><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="pln">
    </span><span class="kwd">private</span><span class="pln"> heroDetailService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroDetailService</span><span class="pun">,</span><span class="pln">
    </span><span class="kwd">private</span><span class="pln"> route</span><span class="pun">:</span><span class="pln">  </span><a href="api/router/ActivatedRoute" class="code-anchor"><span class="typ">ActivatedRoute</span></a><span class="pun">,</span><span class="pln">
    </span><span class="kwd">private</span><span class="pln"> router</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/Router" class="code-anchor"><span class="typ">Router</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">在 <code>TestBed.configureTestingModule</code> 的 <code>providers</code> 中 stub 伪造组件的 <code>HeroDetailService</code> 是不可行的。 这些是<strong>测试模块</strong>的提供商，而非组件的。组件级别的供应商应该在<strong>fixture 级别</strong>准备的依赖注入器。</p><p translation-origin="off">It's not possible to stub the component's <code>HeroDetailService</code> in the <code>providers</code> of the <code>TestBed.configureTestingModule</code>. Those are providers for the <em>testing module</em>, not the component. They prepare the dependency injector at the <em>fixture level</em>.</p><p translation-result="on">Angular 会使用自己的注入器来创建这些组件，这个注入器是夹具的注入器的子注入器。 它使用这个子注入器注册了该组件服务提供商（这里是 <code>HeroDetailService</code> ）。</p><p translation-origin="off">Angular creates the component with its <em>own</em> injector, which is a <em>child</em> of the fixture injector. It registers the component's providers (the <code>HeroDetailService</code> in this case) with the child injector.</p><p translation-result="on">测试没办法从测试夹具的注入器中获取子注入器中的服务，而 <code>TestBed.configureTestingModule</code> 也没法配置它们。</p><p translation-origin="off">A test cannot get to child injector services from the fixture injector. And <code>TestBed.configureTestingModule</code> can't configure them either.</p><p translation-result="on">Angular 始终都在创建真实 <code>HeroDetailService</code> 的实例。</p><p translation-origin="off">Angular has been creating new instances of the real <code>HeroDetailService</code> all along!</p><div class="alert is-helpful"><p translation-result="on">如果 <code>HeroDetailService</code> 向远程服务器发出自己的 XHR 请求，这些测试可能会失败或者超时。 这个远程服务器可能根本不存在。</p><p translation-origin="off">These tests could fail or timeout if the <code>HeroDetailService</code> made its own XHR calls to a remote server. There might not be a remote server to call.</p><p translation-result="on">幸运的是，<code>HeroDetailService</code> 将远程数据访问的责任交给了注入进来的 <code>HeroService</code>。</p><p translation-origin="off">Fortunately, the <code>HeroDetailService</code> delegates responsibility for remote data access to an injected <code>HeroService</code>.</p><code-example path="testing/src/app/hero/hero-detail.service.ts" region="prototype" header="app/hero/hero-detail.service.ts (prototype)" ng-version="9.0.0-rc.11"><div style="display:none">@<a href="api/core/Injectable" class="code-anchor">Injectable</a>() export class HeroDetailService { constructor(private heroService: HeroService) { } /* . . . */ }</div><header class="ng-star-inserted">app/hero/hero-detail.service.ts (prototype)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.service.ts (prototype)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Injectable" class="code-anchor"><span class="lit">Injectable</span></a><span class="pun">()</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">HeroDetailService</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="kwd">private</span><span class="pln"> heroService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroService</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">  </span><span class="pun">}</span><span class="pln">
</span><span class="com">/* . . . */</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on"><a href="guide/testing#feature-module-import">前面的测试配置</a>使用 <code>TestHeroService</code> 替换了真实的 <code>HeroService</code>，它拦截了发往服务器的请求，并伪造了服务器的响应。</p><p translation-origin="off">The <a href="guide/testing#feature-module-import">previous test configuration</a> replaces the real <code>HeroService</code> with a <code>TestHeroService</code> that intercepts server requests and fakes their responses.</p></div><p translation-result="on">如果你没有这么幸运怎么办？如果伪造 <code>HeroService</code> 很难怎么办？如果 <code>HeroDetailService</code> 自己发出服务器请求怎么办？</p><p translation-origin="off">What if you aren't so lucky. What if faking the <code>HeroService</code> is hard? What if <code>HeroDetailService</code> makes its own server requests?</p><p translation-result="on"><code>TestBed.overrideComponent</code> 方法可以将组件的 <code>providers</code> 替换为容易管理的<strong>测试替身</strong>，参见下面的变体准备代码：</p><p translation-origin="off">The <code>TestBed.overrideComponent</code> method can replace the component's <code>providers</code> with easy-to-manage <em>test doubles</em> as seen in the following setup variation:</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="setup-override" header="app/hero/hero-detail.component.spec.ts (Override setup)" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { const routerSpy = createRouterSpy(); TestBed.configureTestingModule({ imports: [ HeroModule ], providers: [ { provide: <a href="api/router/ActivatedRoute" class="code-anchor">ActivatedRoute</a>, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: <a href="api/router/RouterOutlet#activatedRoute" class="code-anchor">activatedRoute</a> }, { provide: <a href="api/router/Router" class="code-anchor">Router</a>, <a href="api/core/ValueSansProvider#useValue" class="code-anchor">useValue</a>: routerSpy}, ] }) // Override component's own provider .overrideComponent(HeroDetailComponent, { set: { providers: [ { provide: HeroDetailService, useClass: HeroDetailServiceSpy } ] } }) .compileComponents(); }));</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (Override setup)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (Override setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> routerSpy </span><span class="pun">=</span><span class="pln"> createRouterSpy</span><span class="pun">();</span><span class="pln">

  </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    imports</span><span class="pun">:</span><span class="pln">   </span><span class="pun">[</span><span class="pln"> </span><span class="typ">HeroModule</span><span class="pln"> </span><span class="pun">],</span><span class="pln">
    providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/ActivatedRoute" class="code-anchor"><span class="typ">ActivatedRoute</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> </span><a href="api/router/RouterOutlet#activatedRoute" class="code-anchor"><span class="pln">activatedRoute</span></a><span class="pln"> </span><span class="pun">},</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/Router" class="code-anchor"><span class="typ">Router</span></a><span class="pun">,</span><span class="pln">         </span><a href="api/core/ValueSansProvider#useValue" class="code-anchor"><span class="pln">useValue</span></a><span class="pun">:</span><span class="pln"> routerSpy</span><span class="pun">},</span><span class="pln">
    </span><span class="pun">]</span><span class="pln">
  </span><span class="pun">})</span><span class="pln">

  </span><span class="com">// Override component's own provider</span><span class="pln">
  </span><span class="pun">.</span><span class="pln">overrideComponent</span><span class="pun">(</span><span class="typ">HeroDetailComponent</span><span class="pun">,</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">set</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
      providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
        </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroDetailService</span><span class="pun">,</span><span class="pln"> useClass</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroDetailServiceSpy</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
      </span><span class="pun">]</span><span class="pln">
    </span><span class="pun">}</span><span class="pln">
  </span><span class="pun">})</span><span class="pln">

  </span><span class="pun">.</span><span class="pln">compileComponents</span><span class="pun">();</span><span class="pln">
</span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><p translation-result="on">注意，<code>TestBed.configureTestingModule</code> 不再提供（伪造的）<code>HeroService</code>，因为<a href="guide/testing#spy-stub">并不需要</a>。</p><p translation-origin="off">Notice that <code>TestBed.configureTestingModule</code> no longer provides a (fake) <code>HeroService</code> because it's <a href="guide/testing#spy-stub">not needed</a>.</p><a id="override-component-method"></a><h4 id="the-overridecomponent-method" translation-result="on"><code>overrideComponent</code> 方法<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-overridecomponent-method"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="the-overridecomponent-method">The <em>overrideComponent</em> method<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-overridecomponent-method"><i class="material-icons">link</i></a></h4><p translation-result="on">注意这个 <code>overrideComponent</code> 方法。</p><p translation-origin="off">Focus on the <code>overrideComponent</code> method.</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="override-component-method" header="app/hero/hero-detail.component.spec.ts (overrideComponent)" ng-version="9.0.0-rc.11"><div style="display:none">.overrideComponent(HeroDetailComponent, { set: { providers: [ { provide: HeroDetailService, useClass: HeroDetailServiceSpy } ] } })</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (overrideComponent)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (overrideComponent)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pun">.</span><span class="pln">overrideComponent</span><span class="pun">(</span><span class="typ">HeroDetailComponent</span><span class="pun">,</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">set</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
      </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroDetailService</span><span class="pun">,</span><span class="pln"> useClass</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroDetailServiceSpy</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
    </span><span class="pun">]</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">})</span></code>
    </pre></aio-code></code-example><p translation-result="on">它接受两个参数：要改写的组件类型（<code>HeroDetailComponent</code>），以及用于改写的元数据对象。 <a href="guide/testing#metadata-override-object">用于改写的元数据对象</a>是一个泛型，其定义如下：</p><p translation-origin="off">It takes two arguments: the component type to override (<code>HeroDetailComponent</code>) and an override metadata object. The <a href="guide/testing#metadata-override-object">override metadata object</a> is a generic defined as follows:</p><code-example language="javascript" ng-version="9.0.0-rc.11"><div style="display:none">type <a href="api/core/testing/MetadataOverride" class="code-anchor">MetadataOverride</a>&lt;T&gt; = { add?: Partial&lt;T&gt;; remove?: Partial&lt;T&gt;; set?: Partial&lt;T&gt;; };</div><aio-code><pre class="lang-javascript prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">type </span><a href="api/core/testing/MetadataOverride" class="code-anchor"><span class="typ">MetadataOverride</span></a><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  add</span><span class="pun">?:</span><span class="pln"> </span><span class="typ">Partial</span><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;;</span><span class="pln">
  remove</span><span class="pun">?:</span><span class="pln"> </span><span class="typ">Partial</span><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;;</span><span class="pln">
  </span><span class="kwd">set</span><span class="pun">?:</span><span class="pln"> </span><span class="typ">Partial</span><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;;</span><span class="pln">
</span><span class="pun">};</span></code>
    </pre></aio-code></code-example><p translation-result="on">元数据重载对象可以添加和删除元数据属性的项目，也可以彻底重设这些属性。 这个例子重新设置了组件的 <code>providers</code> 元数据。</p><p translation-origin="off">A metadata override object can either add-and-remove elements in metadata properties or completely reset those properties. This example resets the component's <code>providers</code> metadata.</p><p translation-result="on">这个类型参数 <code>T</code> 就是你传给 <code>@<a href="api/core/Component" class="code-anchor">Component</a></code> 装饰器的元数据：</p><p translation-origin="off">The type parameter, <code>T</code>, is the kind of metadata you'd pass to the <code>@<a href="api/core/Component" class="code-anchor">Component</a></code> decorator:</p><code-example language="javascript" ng-version="9.0.0-rc.11"><div style="display:none">selector?: string; template?: string; <a href="api/core/Component#templateUrl" class="code-anchor">templateUrl</a>?: string; providers?: any[]; ...</div><aio-code><pre class="lang-javascript prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">selector</span><span class="pun">?:</span><span class="pln"> string</span><span class="pun">;</span><span class="pln">
template</span><span class="pun">?:</span><span class="pln"> string</span><span class="pun">;</span><span class="pln">
</span><a href="api/core/Component#templateUrl" class="code-anchor"><span class="pln">templateUrl</span></a><span class="pun">?:</span><span class="pln"> string</span><span class="pun">;</span><span class="pln">
providers</span><span class="pun">?:</span><span class="pln"> any</span><span class="pun">[];</span><span class="pln">
</span><span class="pun">...</span></code>
    </pre></aio-code></code-example><a id="spy-stub"></a><h4 id="provide-a-spy-stub-herodetailservicespy" translation-result="on">提供 <code>间谍桩</code> (<code>HeroDetailServiceSpy</code>)<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#provide-a-spy-stub-herodetailservicespy"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="provide-a-spy-stub-herodetailservicespy">Provide a <em>spy stub</em> (<em>HeroDetailServiceSpy</em>)<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#provide-a-spy-stub-herodetailservicespy"><i class="material-icons">link</i></a></h4><p translation-result="on">这个例子把组件的 <code>providers</code> 数组完全替换成了一个包含 <code>HeroDetailServiceSpy</code> 的新数组。</p><p translation-origin="off">This example completely replaces the component's <code>providers</code> array with a new array containing a <code>HeroDetailServiceSpy</code>.</p><p translation-result="on"><code>HeroDetailServiceSpy</code> 是实际 <code>HeroDetailService</code> 服务的桩版本，它伪造了该服务的所有必要特性。 但它既不需要注入也不会委托给低层的 <code>HeroService</code> 服务，因此不用为 <code>HeroService</code> 提供测试替身。</p><p translation-origin="off">The <code>HeroDetailServiceSpy</code> is a stubbed version of the real <code>HeroDetailService</code> that fakes all necessary features of that service. It neither injects nor delegates to the lower level <code>HeroService</code> so there's no need to provide a test double for that.</p><p translation-result="on">通过对该服务的方法进行刺探，<code>HeroDetailComponent</code> 的关联测试将会对 <code>HeroDetailService</code> 是否被调用过进行断言。 因此，这个桩类会把它的方法实现为刺探方法：</p><p translation-origin="off">The related <code>HeroDetailComponent</code> tests will assert that methods of the <code>HeroDetailService</code> were called by spying on the service methods. Accordingly, the stub implements its methods as spies:</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="hds-spy" header="app/hero/hero-detail.component.spec.ts (HeroDetailServiceSpy)" ng-version="9.0.0-rc.11"><div style="display:none">class HeroDetailServiceSpy { testHero: Hero = {id: 42, name: 'Test Hero' }; /* emit cloned test hero */ getHero = jasmine.createSpy('getHero').and.callFake( () =&gt; asyncData(Object.assign({}, this.testHero)) ); /* emit clone of test hero, with <a href="api/core/QueryList#changes" class="code-anchor">changes</a> merged in */ saveHero = jasmine.createSpy('saveHero').and.callFake( (hero: Hero) =&gt; asyncData(Object.assign(this.testHero, hero)) ); }</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (HeroDetailServiceSpy)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (HeroDetailServiceSpy)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">class</span><span class="pln"> </span><span class="typ">HeroDetailServiceSpy</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  testHero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">id</span><span class="pun">:</span><span class="pln"> </span><span class="lit">42</span><span class="pun">,</span><span class="pln"> name</span><span class="pun">:</span><span class="pln"> </span><span class="str">'Test Hero'</span><span class="pln"> </span><span class="pun">};</span><span class="pln">

  </span><span class="com">/* emit cloned test hero */</span><span class="pln">
  getHero </span><span class="pun">=</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="pln">createSpy</span><span class="pun">(</span><span class="str">'getHero'</span><span class="pun">).</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">callFake</span><span class="pun">(</span><span class="pln">
    </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> asyncData</span><span class="pun">(</span><span class="typ">Object</span><span class="pun">.</span><span class="pln">assign</span><span class="pun">({},</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">testHero</span><span class="pun">))</span><span class="pln">
  </span><span class="pun">);</span><span class="pln">

  </span><span class="com">/* emit clone of test hero, with </span><a href="api/core/QueryList#changes" class="code-anchor"><span class="com">changes</span></a><span class="com"> merged in */</span><span class="pln">
  saveHero </span><span class="pun">=</span><span class="pln"> jasmine</span><span class="pun">.</span><span class="pln">createSpy</span><span class="pun">(</span><span class="str">'saveHero'</span><span class="pun">).</span><span class="kwd">and</span><span class="pun">.</span><span class="pln">callFake</span><span class="pun">(</span><span class="pln">
    </span><span class="pun">(</span><span class="pln">hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> asyncData</span><span class="pun">(</span><span class="typ">Object</span><span class="pun">.</span><span class="pln">assign</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">testHero</span><span class="pun">,</span><span class="pln"> hero</span><span class="pun">))</span><span class="pln">
  </span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><a id="override-tests"></a><h4 id="the-override-tests" translation-result="on">改写测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-override-tests"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="the-override-tests">The override tests<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-override-tests"><i class="material-icons">link</i></a></h4><p translation-result="on">现在，测试程序可以通过操控这个 spy-stub 的 <code>testHero</code>，直接控制组件的英雄，并确认那个服务方法被调用过。</p><p translation-origin="off">Now the tests can control the component's hero directly by manipulating the spy-stub's <code>testHero</code> and confirm that service methods were called.</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="override-tests" header="app/hero/hero-detail.component.spec.ts (override tests)" ng-version="9.0.0-rc.11"><div style="display:none">let hdsSpy: HeroDetailServiceSpy; beforeEach(<a href="api/core/testing/async" class="code-anchor">async</a>(() =&gt; { createComponent(); // get the component's injected HeroDetailServiceSpy hdsSpy = fixture.debugElement.injector.get(HeroDetailService) as any; })); it('should have called `getHero`', () =&gt; { expect(hdsSpy.getHero.calls.count()).toBe(1, 'getHero called once'); }); it('should display stub hero\'s name', () =&gt; { expect(page.nameDisplay.textContent).toBe(hdsSpy.testHero.name); }); it('should save stub hero change', <a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>(() =&gt; { const origName = hdsSpy.testHero.name; const newName = 'New Name'; page.nameInput.value = newName; page.nameInput.dispatchEvent(newEvent('input')); // tell Angular expect(component.hero.name).toBe(newName, 'component hero has new name'); expect(hdsSpy.testHero.name).toBe(origName, 'service hero unchanged before save'); click(page.saveBtn); expect(hdsSpy.saveHero.calls.count()).toBe(1, 'saveHero called once'); <a href="api/core/testing/tick" class="code-anchor">tick</a>(); // wait for <a href="api/core/testing/async" class="code-anchor">async</a> save to complete expect(hdsSpy.testHero.name).toBe(newName, 'service hero has new name after save'); expect(page.navigateSpy.calls.any()).toBe(true, 'router.navigate called'); }));</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (override tests)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (override tests)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">let</span><span class="pln"> hdsSpy</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HeroDetailServiceSpy</span><span class="pun">;</span><span class="pln">

beforeEach</span><span class="pun">(</span><a href="api/core/testing/async" class="code-anchor"><span class="kwd">async</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  createComponent</span><span class="pun">();</span><span class="pln">
  </span><span class="com">// get the component's injected HeroDetailServiceSpy</span><span class="pln">
  hdsSpy </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">.</span><span class="pln">injector</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><span class="typ">HeroDetailService</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">as</span><span class="pln"> any</span><span class="pun">;</span><span class="pln">
</span><span class="pun">}));</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should have called `getHero`'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">hdsSpy</span><span class="pun">.</span><span class="pln">getHero</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">count</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">1</span><span class="pun">,</span><span class="pln"> </span><span class="str">'getHero called once'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should display stub hero\'s name'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">nameDisplay</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">hdsSpy</span><span class="pun">.</span><span class="pln">testHero</span><span class="pun">.</span><span class="pln">name</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should save stub hero change'</span><span class="pun">,</span><span class="pln"> </span><a href="api/core/testing/fakeAsync" class="code-anchor"><span class="pln">fakeAsync</span></a><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> origName </span><span class="pun">=</span><span class="pln"> hdsSpy</span><span class="pun">.</span><span class="pln">testHero</span><span class="pun">.</span><span class="pln">name</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> newName </span><span class="pun">=</span><span class="pln"> </span><span class="str">'New Name'</span><span class="pun">;</span><span class="pln">

  page</span><span class="pun">.</span><span class="pln">nameInput</span><span class="pun">.</span><span class="kwd">value</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> newName</span><span class="pun">;</span><span class="pln">
  page</span><span class="pun">.</span><span class="pln">nameInput</span><span class="pun">.</span><span class="pln">dispatchEvent</span><span class="pun">(</span><span class="pln">newEvent</span><span class="pun">(</span><span class="str">'input'</span><span class="pun">));</span><span class="pln"> </span><span class="com">// tell Angular</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">component</span><span class="pun">.</span><span class="pln">hero</span><span class="pun">.</span><span class="pln">name</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">newName</span><span class="pun">,</span><span class="pln"> </span><span class="str">'component hero has new name'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">hdsSpy</span><span class="pun">.</span><span class="pln">testHero</span><span class="pun">.</span><span class="pln">name</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">origName</span><span class="pun">,</span><span class="pln"> </span><span class="str">'service hero unchanged before save'</span><span class="pun">);</span><span class="pln">

  click</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">saveBtn</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">hdsSpy</span><span class="pun">.</span><span class="pln">saveHero</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">count</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">1</span><span class="pun">,</span><span class="pln"> </span><span class="str">'saveHero called once'</span><span class="pun">);</span><span class="pln">

  </span><a href="api/core/testing/tick" class="code-anchor"><span class="pln">tick</span></a><span class="pun">();</span><span class="pln"> </span><span class="com">// wait for </span><a href="api/core/testing/async" class="code-anchor"><span class="com">async</span></a><span class="com"> save to complete</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">hdsSpy</span><span class="pun">.</span><span class="pln">testHero</span><span class="pun">.</span><span class="pln">name</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">newName</span><span class="pun">,</span><span class="pln"> </span><span class="str">'service hero has new name after save'</span><span class="pun">);</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">page</span><span class="pun">.</span><span class="pln">navigateSpy</span><span class="pun">.</span><span class="pln">calls</span><span class="pun">.</span><span class="pln">any</span><span class="pun">()).</span><span class="pln">toBe</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">,</span><span class="pln"> </span><span class="str">'router.navigate called'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}));</span></code>
    </pre></aio-code></code-example><a id="more-overrides"></a><h4 id="more-overrides" translation-result="on">更多的改写<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#more-overrides"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="more-overrides">More overrides<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#more-overrides"><i class="material-icons">link</i></a></h4><p translation-result="on"><code>TestBed.overrideComponent</code> 方法可以在相同或不同的组件中被反复调用。 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 还提供了类似的 <code>overrideDirective</code>、<code>overrideModule</code> 和 <code>overridePipe</code> 方法，用来深入并重载这些其它类的部件。</p><p translation-origin="off">The <code>TestBed.overrideComponent</code> method can be called multiple times for the same or different components. The <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> offers similar <code>overrideDirective</code>, <code>overrideModule</code>, and <code>overridePipe</code> methods for digging into and replacing parts of these other classes.</p><p translation-result="on">自己探索这些选项和组合。</p><p translation-origin="off">Explore the options and combinations on your own.</p><hr><a id="attribute-directive"></a><h2 id="attribute-directive-testing" translation-result="on">属性型指令的测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#attribute-directive-testing"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="attribute-directive-testing">Attribute Directive Testing<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#attribute-directive-testing"><i class="material-icons">link</i></a></h2><p translation-result="on"><strong>属性型指令</strong>修改元素、组件和其它指令的行为。正如它们的名字所示，它们是作为宿主元素的属性来被使用的。</p><p translation-origin="off">An <em>attribute directive</em> modifies the behavior of an element, component or another directive. Its name reflects the way the directive is applied: as an attribute on a host element.</p><p translation-result="on">本例子应用的 <code>HighlightDirective</code> 使用数据绑定的颜色或者默认颜色来设置元素的背景色。 它同时设置元素的 <code>customProperty</code> 属性为 <code>true</code>，这里仅仅是为了显示它能这么做而已，并无其它原因。</p><p translation-origin="off">The sample application's <code>HighlightDirective</code> sets the background color of an element based on either a data bound color or a default color (lightgray). It also sets a custom property of the element (<code>customProperty</code>) to <code>true</code> for no reason other than to show that it can.</p><code-example path="testing/src/app/shared/highlight.directive.ts" header="app/shared/highlight.directive.ts" ng-version="9.0.0-rc.11"><div style="display:none">import { <a href="api/core/Directive" class="code-anchor">Directive</a>, <a href="api/core/ElementRef" class="code-anchor">ElementRef</a>, <a href="api/core/Input" class="code-anchor">Input</a>, <a href="api/core/OnChanges" class="code-anchor">OnChanges</a> } from '@angular/core'; @<a href="api/core/Directive" class="code-anchor">Directive</a>({ selector: '[highlight]' }) /** Set backgroundColor for the attached element to highlight color * and set the element's customProperty to true */ export class HighlightDirective implements <a href="api/core/OnChanges" class="code-anchor">OnChanges</a> { defaultColor = 'rgb(211, 211, 211)'; // lightgray @<a href="api/core/Input" class="code-anchor">Input</a>('highlight') bgColor: string; constructor(private el: <a href="api/core/ElementRef" class="code-anchor">ElementRef</a>) { el.nativeElement.style.customProperty = true; } ngOnChanges() { this.el.nativeElement.style.backgroundColor = this.bgColor || this.defaultColor; } }</div><header class="ng-star-inserted">app/shared/highlight.directive.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/shared/highlight.directive.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/Directive" class="code-anchor"><span class="typ">Directive</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/ElementRef" class="code-anchor"><span class="typ">ElementRef</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/Input" class="code-anchor"><span class="typ">Input</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/OnChanges" class="code-anchor"><span class="typ">OnChanges</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core'</span><span class="pun">;</span><span class="pln">

</span><span class="lit">@</span><a href="api/core/Directive" class="code-anchor"><span class="lit">Directive</span></a><span class="pun">({</span><span class="pln"> selector</span><span class="pun">:</span><span class="pln"> </span><span class="str">'[highlight]'</span><span class="pln"> </span><span class="pun">})</span><span class="pln">
</span><span class="com">/** Set backgroundColor for the attached element to highlight color
 *  and set the element's customProperty to true */</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">HighlightDirective</span><span class="pln"> </span><span class="kwd">implements</span><span class="pln"> </span><a href="api/core/OnChanges" class="code-anchor"><span class="typ">OnChanges</span></a><span class="pln"> </span><span class="pun">{</span><span class="pln">

  defaultColor </span><span class="pun">=</span><span class="pln">  </span><span class="str">'rgb(211, 211, 211)'</span><span class="pun">;</span><span class="pln"> </span><span class="com">// lightgray</span><span class="pln">

  </span><span class="lit">@</span><a href="api/core/Input" class="code-anchor"><span class="lit">Input</span></a><span class="pun">(</span><span class="str">'highlight'</span><span class="pun">)</span><span class="pln"> bgColor</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">;</span><span class="pln">

  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="kwd">private</span><span class="pln"> el</span><span class="pun">:</span><span class="pln"> </span><a href="api/core/ElementRef" class="code-anchor"><span class="typ">ElementRef</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    el</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">style</span><span class="pun">.</span><span class="pln">customProperty </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">

  ngOnChanges</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">el</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">style</span><span class="pun">.</span><span class="pln">backgroundColor </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">bgColor </span><span class="pun">||</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">defaultColor</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">它的使用贯穿整个应用，也许最简单的使用在 <code>AboutComponent</code> 里：</p><p translation-origin="off">It's used throughout the application, perhaps most simply in the <code>AboutComponent</code>:</p><code-example path="testing/src/app/about/about.component.ts" header="app/about/about.component.ts" ng-version="9.0.0-rc.11"><div style="display:none">import { <a href="api/core/Component" class="code-anchor">Component</a> } from '@angular/core'; @<a href="api/core/Component" class="code-anchor">Component</a>({ template: ` &lt;h2 highlight="skyblue"&gt;About&lt;/h2&gt; &lt;h3&gt;Quote of the day:&lt;/h3&gt; &lt;twain-quote&gt;&lt;/twain-quote&gt; ` }) export class AboutComponent { }</div><header class="ng-star-inserted">app/about/about.component.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/about/about.component.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/Component" class="code-anchor"><span class="typ">Component</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core'</span><span class="pun">;</span><span class="pln">
</span><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">
  </span><span class="kwd">template</span><span class="pun">:</span><span class="pln"> </span><span class="str">`
  &lt;h2 highlight="skyblue"&gt;About&lt;/h2&gt;
  &lt;h3&gt;Quote of the day:&lt;/h3&gt;
  &lt;twain-quote&gt;&lt;/twain-quote&gt;
  `</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">AboutComponent</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">要想在 <code>AboutComponent</code> 中测试 <code>HighlightDirective</code> 的具体用法，只要使用在<a href="guide/testing#nested-component-tests">“浅层测试”</a>部分用过的技术即可。</p><p translation-origin="off">Testing the specific use of the <code>HighlightDirective</code> within the <code>AboutComponent</code> requires only the techniques explored above (in particular the <a href="guide/testing#nested-component-tests">"Shallow test"</a> approach).</p><code-example path="testing/src/app/about/about.component.spec.ts" region="tests" header="app/about/about.component.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(() =&gt; { fixture = TestBed.configureTestingModule({ declarations: [ AboutComponent, HighlightDirective], schemas: [ <a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor">NO_ERRORS_SCHEMA</a> ] }) .createComponent(AboutComponent); fixture.detectChanges(); // initial binding }); it('should have skyblue &lt;h2&gt;', () =&gt; { const h2: HTMLElement = fixture.nativeElement.querySelector('h2'); const bgColor = h2.style.backgroundColor; expect(bgColor).toBe('skyblue'); });</div><header class="ng-star-inserted">app/about/about.component.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/about/about.component.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">AboutComponent</span><span class="pun">,</span><span class="pln"> </span><span class="typ">HighlightDirective</span><span class="pun">],</span><span class="pln">
    schemas</span><span class="pun">:</span><span class="pln">      </span><span class="pun">[</span><span class="pln"> </span><a href="api/core/NO_ERRORS_SCHEMA" class="code-anchor"><span class="pln">NO_ERRORS_SCHEMA</span></a><span class="pln"> </span><span class="pun">]</span><span class="pln">
  </span><span class="pun">})</span><span class="pln">
  </span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">AboutComponent</span><span class="pun">);</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// initial binding</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should have skyblue &lt;h2&gt;'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> h2</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'h2'</span><span class="pun">);</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> bgColor </span><span class="pun">=</span><span class="pln"> h2</span><span class="pun">.</span><span class="pln">style</span><span class="pun">.</span><span class="pln">backgroundColor</span><span class="pun">;</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">bgColor</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'skyblue'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">但是，测试单一的用例一般无法探索该指令的全部能力。 查找和测试所有使用该指令的组件非常繁琐和脆弱，并且通常无法覆盖所有组件。</p><p translation-origin="off">However, testing a single use case is unlikely to explore the full range of a directive's capabilities. Finding and testing all components that use the directive is tedious, brittle, and almost as unlikely to afford full coverage.</p><p translation-result="on"><em>只针对类的测试</em>可能很有用， 但是像这个一样的属性型指令肯定要操纵 DOM。 隔离出的单元测试不能接触 DOM，因此也就没办法证明该指令的有效性。</p><p translation-origin="off"><em>Class-only tests</em> might be helpful, but attribute directives like this one tend to manipulate the DOM. Isolated unit tests don't touch the DOM and, therefore, do not inspire confidence in the directive's efficacy.</p><p translation-result="on">更好的方法是创建一个能展示该指令所有用法的人造测试组件。</p><p translation-origin="off">A better solution is to create an artificial test component that demonstrates all ways to apply the directive.</p><code-example path="testing/src/app/shared/highlight.directive.spec.ts" region="test-component" header="app/shared/highlight.directive.spec.ts (TestComponent)" ng-version="9.0.0-rc.11"><div style="display:none">@<a href="api/core/Component" class="code-anchor">Component</a>({ template: ` &lt;h2 highlight="yellow"&gt;Something Yellow&lt;/h2&gt; &lt;h2 highlight&gt;The Default (Gray)&lt;/h2&gt; &lt;h2&gt;No Highlight&lt;/h2&gt; &lt;input #box [highlight]="box.value" value="cyan"/&gt;` }) class TestComponent { }</div><header class="ng-star-inserted">app/shared/highlight.directive.spec.ts (TestComponent)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/shared/highlight.directive.spec.ts (TestComponent)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Component" class="code-anchor"><span class="lit">Component</span></a><span class="pun">({</span><span class="pln">
  </span><span class="kwd">template</span><span class="pun">:</span><span class="pln"> </span><span class="str">`
  &lt;h2 highlight="yellow"&gt;Something Yellow&lt;/h2&gt;
  &lt;h2 highlight&gt;The Default (Gray)&lt;/h2&gt;
  &lt;h2&gt;No Highlight&lt;/h2&gt;
  &lt;input #box [highlight]="box.value" value="cyan"/&gt;`</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">class</span><span class="pln"> </span><span class="typ">TestComponent</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">}</span></code>
    </pre></aio-code></code-example><div class="lightbox"><img src="generated/images/guide/testing/highlight-directive-spec.png" alt="HighlightDirective spec in action" width="200" height="159"></div><div class="alert is-helpful"><p translation-result="on"><code>&lt;input&gt;</code> 用例将 <code>HighlightDirective</code> 绑定到输入框里输入的颜色名字。 初始只是单词“cyan”，所以输入框的背景色应该是 cyan。</p><p translation-origin="off">The <code>&lt;input&gt;</code> case binds the <code>HighlightDirective</code> to the name of a color value in the input box. The initial value is the word "cyan" which should be the background color of the input box.</p></div><p translation-result="on">下面是一些该组件的测试程序：</p><p translation-origin="off">Here are some tests of this component:</p><code-example path="testing/src/app/shared/highlight.directive.spec.ts" region="selected-tests" header="app/shared/highlight.directive.spec.ts (selected tests)" ng-version="9.0.0-rc.11"><div style="display:none">beforeEach(() =&gt; { fixture = TestBed.configureTestingModule({ declarations: [ HighlightDirective, TestComponent ] }) .createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached HighlightDirective des = fixture.debugElement.queryAll(By.directive(HighlightDirective)); // the h2 without the HighlightDirective bareH2 = fixture.debugElement.query(By.css('h2:not([highlight])')); }); // color tests it('should have three highlighted elements', () =&gt; { expect(des.length).toBe(3); }); it('should color 1st &lt;h2&gt; background "yellow"', () =&gt; { const bgColor = des[0].nativeElement.style.backgroundColor; expect(bgColor).toBe('yellow'); }); it('should color 2nd &lt;h2&gt; background w/ default color', () =&gt; { const dir = des[1].injector.get(HighlightDirective) as HighlightDirective; const bgColor = des[1].nativeElement.style.backgroundColor; expect(bgColor).toBe(dir.defaultColor); }); it('should bind &lt;input&gt; background to value color', () =&gt; { // easier to work with nativeElement const input = des[2].nativeElement as HTMLInputElement; expect(input.style.backgroundColor).toBe('cyan', 'initial backgroundColor'); // dispatch a DOM event so that Angular responds to the input value change. input.value = 'green'; input.dispatchEvent(newEvent('input')); fixture.detectChanges(); expect(input.style.backgroundColor).toBe('green', 'changed backgroundColor'); }); it('bare &lt;h2&gt; should not have a customProperty', () =&gt; { expect(bareH2.properties['customProperty']).toBeUndefined(); });</div><header class="ng-star-inserted">app/shared/highlight.directive.spec.ts (selected tests)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/shared/highlight.directive.spec.ts (selected tests)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  fixture </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
    declarations</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">HighlightDirective</span><span class="pun">,</span><span class="pln"> </span><span class="typ">TestComponent</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
  </span><span class="pun">})</span><span class="pln">
  </span><span class="pun">.</span><span class="pln">createComponent</span><span class="pun">(</span><span class="typ">TestComponent</span><span class="pun">);</span><span class="pln">

  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln"> </span><span class="com">// initial binding</span><span class="pln">

  </span><span class="com">// all elements with an attached HighlightDirective</span><span class="pln">
  des </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">.</span><span class="pln">queryAll</span><span class="pun">(</span><span class="typ">By</span><span class="pun">.</span><span class="pln">directive</span><span class="pun">(</span><span class="typ">HighlightDirective</span><span class="pun">));</span><span class="pln">

  </span><span class="com">// the h2 without the HighlightDirective</span><span class="pln">
  bareH2 </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">.</span><span class="pln">query</span><span class="pun">(</span><span class="typ">By</span><span class="pun">.</span><span class="pln">css</span><span class="pun">(</span><span class="str">'h2:not([highlight])'</span><span class="pun">));</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

</span><span class="com">// color tests</span><span class="pln">
it</span><span class="pun">(</span><span class="str">'should have three highlighted elements'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">des</span><span class="pun">.</span><span class="pln">length</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="lit">3</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should color 1st &lt;h2&gt; background "yellow"'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> bgColor </span><span class="pun">=</span><span class="pln"> des</span><span class="pun">[</span><span class="lit">0</span><span class="pun">].</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">style</span><span class="pun">.</span><span class="pln">backgroundColor</span><span class="pun">;</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">bgColor</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'yellow'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should color 2nd &lt;h2&gt; background w/ default color'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> dir </span><span class="pun">=</span><span class="pln"> des</span><span class="pun">[</span><span class="lit">1</span><span class="pun">].</span><span class="pln">injector</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><span class="typ">HighlightDirective</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">as</span><span class="pln"> </span><span class="typ">HighlightDirective</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> bgColor </span><span class="pun">=</span><span class="pln"> des</span><span class="pun">[</span><span class="lit">1</span><span class="pun">].</span><span class="pln">nativeElement</span><span class="pun">.</span><span class="pln">style</span><span class="pun">.</span><span class="pln">backgroundColor</span><span class="pun">;</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">bgColor</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="pln">dir</span><span class="pun">.</span><span class="pln">defaultColor</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">

it</span><span class="pun">(</span><span class="str">'should bind &lt;input&gt; background to value color'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// easier to work with nativeElement</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> input </span><span class="pun">=</span><span class="pln"> des</span><span class="pun">[</span><span class="lit">2</span><span class="pun">].</span><span class="pln">nativeElement </span><span class="kwd">as</span><span class="pln"> </span><span class="typ">HTMLInputElement</span><span class="pun">;</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">input</span><span class="pun">.</span><span class="pln">style</span><span class="pun">.</span><span class="pln">backgroundColor</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'cyan'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'initial backgroundColor'</span><span class="pun">);</span><span class="pln">

  </span><span class="com">// dispatch a DOM event so that Angular responds to the input value change.</span><span class="pln">
  input</span><span class="pun">.</span><span class="kwd">value</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="str">'green'</span><span class="pun">;</span><span class="pln">
  input</span><span class="pun">.</span><span class="pln">dispatchEvent</span><span class="pun">(</span><span class="pln">newEvent</span><span class="pun">(</span><span class="str">'input'</span><span class="pun">));</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">input</span><span class="pun">.</span><span class="pln">style</span><span class="pun">.</span><span class="pln">backgroundColor</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'green'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'changed backgroundColor'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span><span class="pln">


it</span><span class="pun">(</span><span class="str">'bare &lt;h2&gt; should not have a customProperty'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">bareH2</span><span class="pun">.</span><span class="pln">properties</span><span class="pun">[</span><span class="str">'customProperty'</span><span class="pun">]).</span><span class="pln">toBeUndefined</span><span class="pun">();</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">一些技巧值得注意：</p><p translation-origin="off">A few techniques are noteworthy:</p><ul><li><p translation-result="on">当<strong>已知元素类型</strong>时，<code>By.directive</code> 是一种获取拥有这个指令的元素的好方法。</p><p translation-origin="off">The <code>By.directive</code> predicate is a great way to get the elements that have this directive <em>when their element types are unknown</em>.</p></li><li><p translation-result="on"> <code>By.css('h2:not([highlight])')</code> 里的<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:not" target="_blank"><code>:not</code> 伪类（pseudo-class）</a>帮助查找<strong>不带</strong>该指令的 <code>&lt;h2&gt;</code> 元素。<code>By.css('*:not([highlight])')</code> 查找<strong>所有</strong>不带该指令的元素。</p><p translation-origin="off">The <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:not"><code>:not</code> pseudo-class</a> in <code>By.css('h2:not([highlight])')</code> helps find <code>&lt;h2&gt;</code> elements that <em>do not</em> have the directive. <code>By.css('*:not([highlight])')</code> finds <em>any</em> element that does not have the directive.</p></li><li><p translation-result="on"> <code><a href="api/core/DebugElement#styles" class="code-anchor">DebugElement.styles</a></code> 甚至不用借助真实的浏览器也可以访问元素的样式，感谢 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 提供的这层抽象！ 但是如果直接使用 <code>nativeElement</code> 会比这层抽象更简单、更清晰，也可以放心大胆的使用它。</p><p translation-origin="off"><code><a href="api/core/DebugElement#styles" class="code-anchor">DebugElement.styles</a></code> affords access to element styles even in the absence of a real browser, thanks to the <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> abstraction. But feel free to exploit the <code>nativeElement</code> when that seems easier or more clear than the abstraction.</p></li><li><p translation-result="on">Angular 将指令添加到它的元素的注入器中。默认颜色的测试程序使用第二个 <code>&lt;h2&gt;</code> 的注入器来获取它的 <code>HighlightDirective</code> 实例以及它的 <code>defaultColor</code>。</p><p translation-origin="off">Angular adds a directive to the injector of the element to which it is applied. The test for the default color uses the injector of the second <code>&lt;h2&gt;</code> to get its <code>HighlightDirective</code> instance and its <code>defaultColor</code>.</p></li><li><p translation-result="on"> <code><a href="api/core/DebugElement#properties" class="code-anchor">DebugElement.properties</a></code> 让你可以访问由指令设置的自定义属性。</p><p translation-origin="off"><code><a href="api/core/DebugElement#properties" class="code-anchor">DebugElement.properties</a></code> affords access to the artificial custom property that is set by the directive.</p></li></ul><hr><h2 id="pipe-testing" translation-result="on">管道测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#pipe-testing"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="pipe-testing">Pipe Testing<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#pipe-testing"><i class="material-icons">link</i></a></h2><p translation-result="on">管道很容易测试，无需 Angular 测试工具。</p><p translation-origin="off">Pipes are easy to test without the Angular testing utilities.</p><p translation-result="on">管道类有一个方法，<code>transform</code>，用来转换输入值到输出值。 <code>transform</code> 的实现很少与 DOM 交互。 除了 <code>@<a href="api/core/Pipe" class="code-anchor">Pipe</a></code> 元数据和一个接口外，大部分管道不依赖 Angular。</p><p translation-origin="off">A pipe class has one method, <code>transform</code>, that manipulates the input value into a transformed output value. The <code>transform</code> implementation rarely interacts with the DOM. Most pipes have no dependence on Angular other than the <code>@<a href="api/core/Pipe" class="code-anchor">Pipe</a></code> metadata and an interface.</p><p translation-result="on">假设 <code><a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a></code> 将每个单词的第一个字母变成大写。 下面是使用正则表达式实现的简单代码：</p><p translation-origin="off">Consider a <code><a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a></code> that capitalizes the first letter of each word. Here's a naive implementation with a regular expression.</p><code-example path="testing/src/app/shared/title-case.pipe.ts" header="app/shared/title-case.pipe.ts" ng-version="9.0.0-rc.11"><div style="display:none">import { <a href="api/core/Pipe" class="code-anchor">Pipe</a>, <a href="api/core/PipeTransform" class="code-anchor">PipeTransform</a> } from '@angular/core'; @<a href="api/core/Pipe" class="code-anchor">Pipe</a>({name: 'titlecase', pure: true}) /** Transform to <a href="api/platform-browser/Title" class="code-anchor">Title</a> Case: uppercase the first letter of the words in a string.*/ export class <a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a> implements <a href="api/core/PipeTransform" class="code-anchor">PipeTransform</a> { transform(input: string): string { return input.length === 0 ? '' : input.replace(/\w\S*/g, (txt =&gt; txt[0].toUpperCase() + txt.substr(1).toLowerCase() )); } }</div><header class="ng-star-inserted">app/shared/title-case.pipe.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/shared/title-case.pipe.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/Pipe" class="code-anchor"><span class="typ">Pipe</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/core/PipeTransform" class="code-anchor"><span class="typ">PipeTransform</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core'</span><span class="pun">;</span><span class="pln">

</span><span class="lit">@</span><a href="api/core/Pipe" class="code-anchor"><span class="lit">Pipe</span></a><span class="pun">({</span><span class="pln">name</span><span class="pun">:</span><span class="pln"> </span><span class="str">'titlecase'</span><span class="pun">,</span><span class="pln"> pure</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">})</span><span class="pln">
</span><span class="com">/** Transform to </span><a href="api/platform-browser/Title" class="code-anchor"><span class="com">Title</span></a><span class="com"> Case: uppercase the first letter of the words in a string.*/</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><a href="api/common/TitleCasePipe" class="code-anchor"><span class="typ">TitleCasePipe</span></a><span class="pln"> </span><span class="kwd">implements</span><span class="pln"> </span><a href="api/core/PipeTransform" class="code-anchor"><span class="typ">PipeTransform</span></a><span class="pln"> </span><span class="pun">{</span><span class="pln">
  transform</span><span class="pun">(</span><span class="pln">input</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">):</span><span class="pln"> </span><span class="kwd">string</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> input</span><span class="pun">.</span><span class="pln">length </span><span class="pun">===</span><span class="pln"> </span><span class="lit">0</span><span class="pln"> </span><span class="pun">?</span><span class="pln"> </span><span class="str">''</span><span class="pln"> </span><span class="pun">:</span><span class="pln">
      input</span><span class="pun">.</span><span class="pln">replace</span><span class="pun">(</span><span class="str">/\w\S*/</span><span class="pln">g</span><span class="pun">,</span><span class="pln"> </span><span class="pun">(</span><span class="pln">txt </span><span class="pun">=&gt;</span><span class="pln"> txt</span><span class="pun">[</span><span class="lit">0</span><span class="pun">].</span><span class="pln">toUpperCase</span><span class="pun">()</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> txt</span><span class="pun">.</span><span class="pln">substr</span><span class="pun">(</span><span class="lit">1</span><span class="pun">).</span><span class="pln">toLowerCase</span><span class="pun">()</span><span class="pln"> </span><span class="pun">));</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">任何使用正则表达式的类都值得彻底的进行测试。 使用 Jasmine 来探索预期的用例和极端的用例。</p><p translation-origin="off">Anything that uses a regular expression is worth testing thoroughly. Use simple Jasmine to explore the expected cases and the edge cases.</p><code-example path="testing/src/app/shared/title-case.pipe.spec.ts" region="excerpt" header="app/shared/title-case.pipe.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">describe('<a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a>', () =&gt; { // This pipe is a pure, stateless function so no need for BeforeEach let pipe = new <a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a>(); it('transforms "abc" to "Abc"', () =&gt; { expect(pipe.transform('abc')).toBe('Abc'); }); it('transforms "abc def" to "Abc Def"', () =&gt; { expect(pipe.transform('abc def')).toBe('Abc Def'); }); // ... more tests ... });</div><header class="ng-star-inserted">app/shared/title-case.pipe.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/shared/title-case.pipe.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">describe</span><span class="pun">(</span><span class="str">'</span><a href="api/common/TitleCasePipe" class="code-anchor"><span class="str">TitleCasePipe</span></a><span class="str">'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// This pipe is a pure, stateless function so no need for BeforeEach</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> pipe </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><a href="api/common/TitleCasePipe" class="code-anchor"><span class="typ">TitleCasePipe</span></a><span class="pun">();</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'transforms "abc" to "Abc"'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">pipe</span><span class="pun">.</span><span class="pln">transform</span><span class="pun">(</span><span class="str">'abc'</span><span class="pun">)).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'Abc'</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  it</span><span class="pun">(</span><span class="str">'transforms "abc def" to "Abc Def"'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    expect</span><span class="pun">(</span><span class="pln">pipe</span><span class="pun">.</span><span class="pln">transform</span><span class="pun">(</span><span class="str">'abc def'</span><span class="pun">)).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'Abc Def'</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  </span><span class="com">// ... more tests ...</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><a id="write-tests"></a><h4 id="write-dom-tests-too" translation-result="on">也能编写 DOM 测试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#write-dom-tests-too"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="write-dom-tests-too">Write DOM tests too<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#write-dom-tests-too"><i class="material-icons">link</i></a></h4><p translation-result="on">有些管道的测试程序是<strong>孤立的</strong>。 它们不能验证 <code><a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a></code> 是否在应用到组件上时是否工作正常。</p><p translation-origin="off">These are tests of the pipe <em>in isolation</em>. They can't tell if the <code><a href="api/common/TitleCasePipe" class="code-anchor">TitleCasePipe</a></code> is working properly as applied in the application components.</p><p translation-result="on">考虑像这样添加组件测试程序：</p><p translation-origin="off">Consider adding component tests such as this one:</p><code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="title-case-pipe" header="app/hero/hero-detail.component.spec.ts (pipe test)" ng-version="9.0.0-rc.11"><div style="display:none">it('should convert hero name to <a href="api/platform-browser/Title" class="code-anchor">Title</a> Case', () =&gt; { // get the name's input and display elements from the DOM const hostElement = fixture.nativeElement; const nameInput: HTMLInputElement = hostElement.querySelector('input'); const nameDisplay: HTMLElement = hostElement.querySelector('span'); // simulate user entering a new name into the input box nameInput.value = 'quick BROWN fOx'; // dispatch a DOM event so that Angular learns of input value change. // use newEvent utility function (not provided by Angular) for better <a href="api/animations/browser" class="code-anchor">browser</a> compatibility nameInput.dispatchEvent(newEvent('input')); // Tell Angular to <a href="api/forms/NgModel#update" class="code-anchor">update</a> the display binding through the title pipe fixture.detectChanges(); expect(nameDisplay.textContent).toBe('Quick Brown Fox'); });</div><header class="ng-star-inserted">app/hero/hero-detail.component.spec.ts (pipe test)</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-detail.component.spec.ts (pipe test)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'should convert hero name to </span><a href="api/platform-browser/Title" class="code-anchor"><span class="str">Title</span></a><span class="str"> Case'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// get the name's input and display elements from the DOM</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> hostElement </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">nativeElement</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> nameInput</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLInputElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> hostElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'input'</span><span class="pun">);</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> nameDisplay</span><span class="pun">:</span><span class="pln"> </span><span class="typ">HTMLElement</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> hostElement</span><span class="pun">.</span><span class="pln">querySelector</span><span class="pun">(</span><span class="str">'span'</span><span class="pun">);</span><span class="pln">

  </span><span class="com">// simulate user entering a new name into the input box</span><span class="pln">
  nameInput</span><span class="pun">.</span><span class="kwd">value</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="str">'quick BROWN  fOx'</span><span class="pun">;</span><span class="pln">

  </span><span class="com">// dispatch a DOM event so that Angular learns of input value change.</span><span class="pln">
  </span><span class="com">// use newEvent utility function (not provided by Angular) for better </span><a href="api/animations/browser" class="code-anchor"><span class="com">browser</span></a><span class="com"> compatibility</span><span class="pln">
  nameInput</span><span class="pun">.</span><span class="pln">dispatchEvent</span><span class="pun">(</span><span class="pln">newEvent</span><span class="pun">(</span><span class="str">'input'</span><span class="pun">));</span><span class="pln">

  </span><span class="com">// Tell Angular to </span><a href="api/forms/NgModel#update" class="code-anchor"><span class="com">update</span></a><span class="com"> the display binding through the title pipe</span><span class="pln">
  fixture</span><span class="pun">.</span><span class="pln">detectChanges</span><span class="pun">();</span><span class="pln">

  expect</span><span class="pun">(</span><span class="pln">nameDisplay</span><span class="pun">.</span><span class="pln">textContent</span><span class="pun">).</span><span class="pln">toBe</span><span class="pun">(</span><span class="str">'Quick Brown  Fox'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><hr><a id="test-debugging"></a><h2 id="test-debugging" translation-result="on">测试程序的调试<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#test-debugging"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="test-debugging">Test debugging<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#test-debugging"><i class="material-icons">link</i></a></h2><p translation-result="on">在浏览器中，像调试应用一样调试测试程序 spec。</p><p translation-origin="off">Debug specs in the browser in the same way that you debug an application.</p><ol><li><p translation-result="on">显示 <code>Karma</code> 的浏览器窗口（之前被隐藏了）。</p><p translation-origin="off">Reveal the Karma browser window (hidden earlier).</p></li><li><p translation-result="on">点击“DEBUG”按钮；它打开一页新浏览器标签并重新开始运行测试程序</p><p translation-origin="off">Click the <strong>DEBUG</strong> button; it opens a new browser tab and re-runs the tests.</p></li><li><p translation-result="on">打开浏览器的“Developer Tools”(Windows 上的 Ctrl-Shift-I 或者 macOS 上的 Command-Option-I)。</p><p translation-origin="off">Open the browser's “Developer Tools” (<code>Ctrl-Shift-I</code> on Windows; <code>Command-Option-I</code> in macOS).</p></li><li><p translation-result="on">选择“sources”页</p><p translation-origin="off">Pick the "sources" section.</p></li><li><p translation-result="on">打开 <code>1st.spec.ts</code> 测试文件（Control/Command-P, 然后输入文件名字）。</p><p translation-origin="off">Open the <code>1st.spec.ts</code> test file (Control/Command-P, then start typing the name of the file).</p></li><li><p translation-result="on">在测试程序中设置断点。</p><p translation-origin="off">Set a breakpoint in the test.</p></li><li><p translation-result="on">刷新浏览器...然后它就会停在断点上。</p><p translation-origin="off">Refresh the browser, and it stops at the breakpoint.</p></li></ol><div class="lightbox"><img src="generated/images/guide/testing/karma-1st-spec-debug.png" alt="Karma debugging" width="700" height="150"></div><hr><a id="atu-apis"></a><h2 id="testing-utility-apis" translation-result="on">测试工具 API<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-utility-apis"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="testing-utility-apis">Testing Utility APIs<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testing-utility-apis"><i class="material-icons">link</i></a></h2><p translation-result="on">本节将最有用的 Angular 测试功能提取出来，并总结了它们的作用。</p><p translation-origin="off">This section takes inventory of the most useful Angular testing features and summarizes what they do.</p><p translation-result="on">Angular 的测试工具集包括 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>、<code><a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a></code> 和一些用来控制测试环境的便捷函数。 <a href="guide/testing#testbed-api-summary"><code>TestBed</code></a>和 <a href="guide/testing#component-fixture-api-summary"><code>ComponentFixture</code></a>部分单独讲过它们。</p><p translation-origin="off">The Angular testing utilities include the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>, the <code><a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a></code>, and a handful of functions that control the test environment. The <a href="guide/testing#testbed-api-summary"><em>TestBed</em></a> and <a href="guide/testing#component-fixture-api-summary"><em>ComponentFixture</em></a> classes are covered separately.</p><p translation-result="on">下面是一些独立函数的总结，以使用频率排序：</p><p translation-origin="off">Here's a summary of the stand-alone functions, in order of likely utility:</p><table><tbody><tr><th><p translation-result="on">函数</p><p translation-origin="off">Function</p></th><th><p translation-result="on">说明</p><p translation-origin="off">Description</p></th></tr><tr><td style="vertical-align:top"><p> <code><a href="api/core/testing/async" class="code-anchor">async</a></code></p></td><td><p translation-result="on">在一个特殊的<em> async 测试区域</em>中运行测试（<code>it</code>）的函数体或准备函数（<code>beforeEach</code>）。 参见<a href="guide/testing#async">前面的讨论</a>。</p><p translation-origin="off">Runs the body of a test (<code>it</code>) or setup (<code>beforeEach</code>) function within a special <em>async test zone</em>. See <a href="guide/testing#async">discussion above</a>.</p></td></tr><tr><td style="vertical-align:top"><p> <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a></code></p></td><td><p translation-result="on">在一个特殊的<em> fakeAsync 测试区域</em>中运行测试（<code>it</code>）的函数体，以便启用线性风格的控制流。 参见<a href="guide/testing#fake-async">前面的讨论</a>。</p><p translation-origin="off">Runs the body of a test (<code>it</code>) within a special <em>fakeAsync test zone</em>, enabling a linear control flow coding style. See <a href="guide/testing#fake-async">discussion above</a>.</p></td></tr><tr><td style="vertical-align:top"><p> <code><a href="api/core/testing/tick" class="code-anchor">tick</a></code></p></td><td><p translation-result="on">通过在<em> fakeAsync 测试区域</em>中刷新定时器和微任务（micro-task）队列来仿真时间的流逝以及异步活动的完成。</p><p translation-origin="off">Simulates the passage of time and the completion of pending asynchronous activities by flushing both <em>timer</em> and <em>micro-task</em> queues within the <em>fakeAsync test zone</em>.</p><div class="alert is-helpful"><p translation-result="on">好奇和执着的读者可能会喜欢这篇长博客： "<a href="https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/" target="_blank"><em>Tasks, microtasks, queues and schedules</em></a>".</p><p translation-origin="off">The curious, dedicated reader might enjoy this lengthy blog post, <a href="https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/">"<em>Tasks, microtasks, queues and schedules</em>"</a>.</p></div><p translation-result="on">接受一个可选参数，它可以把虚拟时钟往前推进特定的微秒数。 清除调度到那个时间帧中的异步活动。 参见<a href="guide/testing#tick">前面的讨论</a>。</p><p translation-origin="off">Accepts an optional argument that moves the virtual clock forward by the specified number of milliseconds, clearing asynchronous activities scheduled within that timeframe. See <a href="guide/testing#tick">discussion above</a>.</p></td></tr><tr><td style="vertical-align:top"><p> <code>inject</code></p></td><td><p translation-result="on">从当前的 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 注入器中把一个或多个服务注入到一个测试函数中。 它不能用于注入组件自身提供的服务。 参见 <a href="guide/testing#get-injected-services"><code>debugElement.injector</code></a>部分的讨论。</p><p translation-origin="off">Injects one or more services from the current <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> injector into a test function. It cannot inject a service provided by the component itself. See discussion of the <a href="guide/testing#get-injected-services">debugElement.injector</a>.</p></td></tr><tr><td style="vertical-align:top"><p> <code><a href="api/core/testing/discardPeriodicTasks" class="code-anchor">discardPeriodicTasks</a></code></p></td><td><p translation-result="on">当 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a></code> 测试程序以正在运行的计时器事件<strong>任务</strong>（排队中的 <code>setTimeOut</code> 和 <code>setInterval</code> 的回调）结束时， 测试会失败，并显示一条明确的错误信息。</p><p translation-origin="off">When a <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> test ends with pending timer event <em>tasks</em> (queued <code>setTimeOut</code> and <code>setInterval</code> callbacks), the test fails with a clear error message.</p><p translation-result="on">一般来讲，测试程序应该以无排队任务结束。 当待执行计时器任务存在时，调用 <code><a href="api/core/testing/discardPeriodicTasks" class="code-anchor">discardPeriodicTasks</a></code> 来触发<strong>任务</strong>队列，防止该错误发生。</p><p translation-origin="off">In general, a test should end with no queued tasks. When pending timer tasks are expected, call <code><a href="api/core/testing/discardPeriodicTasks" class="code-anchor">discardPeriodicTasks</a></code> to flush the <em>task</em> queue and avoid the error.</p></td></tr><tr><td style="vertical-align:top"><p> <code><a href="api/core/testing/flushMicrotasks" class="code-anchor">flushMicrotasks</a></code></p></td><td><p translation-result="on">当 <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a></code> 测试程序以待执行<strong>微任务</strong>（比如未解析的承诺）结束时，测试会失败并显示明确的错误信息。</p><p translation-origin="off">When a <code><a href="api/core/testing/fakeAsync" class="code-anchor">fakeAsync</a>()</code> test ends with pending <em>micro-tasks</em> such as unresolved promises, the test fails with a clear error message.</p><p translation-result="on">一般来说，测试应该等待微任务结束。 当待执行微任务存在时，调用 <code><a href="api/core/testing/flushMicrotasks" class="code-anchor">flushMicrotasks</a></code> 来触发<strong>微任务</strong>队列，防止该错误发生。</p><p translation-origin="off">In general, a test should wait for micro-tasks to finish. When pending microtasks are expected, call <code><a href="api/core/testing/flushMicrotasks" class="code-anchor">flushMicrotasks</a></code> to flush the <em>micro-task</em> queue and avoid the error.</p></td></tr><tr><td style="vertical-align:top"><p> <code><a href="api/core/testing/ComponentFixtureAutoDetect" class="code-anchor">ComponentFixtureAutoDetect</a></code></p></td><td><p translation-result="on">一个服务提供商令牌，用于开启<a href="guide/testing#automatic-change-detection">自动变更检测</a>。</p><p translation-origin="off">A provider token for a service that turns on <a href="guide/testing#automatic-change-detection">automatic change detection</a>.</p></td></tr><tr><td style="vertical-align:top"><p> <code><a href="api/core/testing/getTestBed" class="code-anchor">getTestBed</a></code></p></td><td><p translation-result="on">获取当前 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 实例。 通常用不上，因为 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 的静态类方法已经够用。 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 实例有一些很少需要用到的方法，它们没有对应的静态方法。</p><p translation-origin="off">Gets the current instance of the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>. Usually unnecessary because the static class methods of the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> class are typically sufficient. The <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> instance exposes a few rarely used members that are not available as static methods.</p></td></tr></tbody></table><hr><a id="testbed-class-summary"></a><h4 id="testbed-class-summary" translation-result="on"><code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 类小结<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testbed-class-summary"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="testbed-class-summary"><em>TestBed</em> class summary<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#testbed-class-summary"><i class="material-icons">link</i></a></h4><p translation-result="on"><code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 类是 Angular 测试工具的主要类之一。它的 API 很庞大，可能有点过于复杂，直到你一点一点的探索它们。 阅读本章前面的部分，了解了基本的知识以后，再试着了解完整 API。</p><p translation-origin="off">The <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> class is one of the principal Angular testing utilities. Its API is quite large and can be overwhelming until you've explored it, a little at a time. Read the early part of this guide first to get the basics before trying to absorb the full API.</p><p translation-result="on">传给 <code>configureTestingModule</code> 的模块定义是 <code>@<a href="api/core/NgModule" class="code-anchor">NgModule</a></code> 元数据属性的子集。</p><p translation-origin="off">The module definition passed to <code>configureTestingModule</code> is a subset of the <code>@<a href="api/core/NgModule" class="code-anchor">NgModule</a></code> metadata properties.</p><code-example language="javascript" ng-version="9.0.0-rc.11"><div style="display:none">type <a href="api/core/testing/TestModuleMetadata" class="code-anchor">TestModuleMetadata</a> = { providers?: any[]; declarations?: any[]; imports?: any[]; schemas?: Array&lt;<a href="api/core/SchemaMetadata" class="code-anchor">SchemaMetadata</a> | any[]&gt;; };</div><aio-code><pre class="lang-javascript prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">type </span><a href="api/core/testing/TestModuleMetadata" class="code-anchor"><span class="typ">TestModuleMetadata</span></a><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  providers</span><span class="pun">?:</span><span class="pln"> any</span><span class="pun">[];</span><span class="pln">
  declarations</span><span class="pun">?:</span><span class="pln"> any</span><span class="pun">[];</span><span class="pln">
  imports</span><span class="pun">?:</span><span class="pln"> any</span><span class="pun">[];</span><span class="pln">
  schemas</span><span class="pun">?:</span><span class="pln"> </span><span class="typ">Array</span><span class="pun">&lt;</span><a href="api/core/SchemaMetadata" class="code-anchor"><span class="typ">SchemaMetadata</span></a><span class="pln"> </span><span class="pun">|</span><span class="pln"> any</span><span class="pun">[]&gt;;</span><span class="pln">
</span><span class="pun">};</span></code>
    </pre></aio-code></code-example><a id="metadata-override-object"></a><p translation-result="on">每一个重载方法接受一个 <code><a href="api/core/testing/MetadataOverride" class="code-anchor">MetadataOverride</a>&lt;T&gt;</code>，这里 <code>T</code> 是适合这个方法的元数据类型，也就是 <code>@<a href="api/core/NgModule" class="code-anchor">NgModule</a></code>、<code>@<a href="api/core/Component" class="code-anchor">Component</a></code>、<code>@<a href="api/core/Directive" class="code-anchor">Directive</a></code> 或者 <code>@<a href="api/core/Pipe" class="code-anchor">Pipe</a></code> 的参数。</p><p translation-origin="off">Each override method takes a <code><a href="api/core/testing/MetadataOverride" class="code-anchor">MetadataOverride</a>&lt;T&gt;</code> where <code>T</code> is the kind of metadata appropriate to the method, that is, the parameter of an <code>@<a href="api/core/NgModule" class="code-anchor">NgModule</a></code>, <code>@<a href="api/core/Component" class="code-anchor">Component</a></code>, <code>@<a href="api/core/Directive" class="code-anchor">Directive</a></code>, or <code>@<a href="api/core/Pipe" class="code-anchor">Pipe</a></code>.</p><code-example language="javascript" ng-version="9.0.0-rc.11"><div style="display:none">type <a href="api/core/testing/MetadataOverride" class="code-anchor">MetadataOverride</a>&lt;T&gt; = { add?: Partial&lt;T&gt;; remove?: Partial&lt;T&gt;; set?: Partial&lt;T&gt;; };</div><aio-code><pre class="lang-javascript prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">type </span><a href="api/core/testing/MetadataOverride" class="code-anchor"><span class="typ">MetadataOverride</span></a><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  add</span><span class="pun">?:</span><span class="pln"> </span><span class="typ">Partial</span><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;;</span><span class="pln">
  remove</span><span class="pun">?:</span><span class="pln"> </span><span class="typ">Partial</span><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;;</span><span class="pln">
  </span><span class="kwd">set</span><span class="pun">?:</span><span class="pln"> </span><span class="typ">Partial</span><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;;</span><span class="pln">
</span><span class="pun">};</span></code>
    </pre></aio-code></code-example><a id="testbed-methods"></a> <a id="testbed-api-summary"></a><p translation-result="on"><code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 的 API 包含了一系列静态类方法，它们更新或者引用<strong>全局</strong>的 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 实例。</p><p translation-origin="off">The <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> API consists of static class methods that either update or reference a <em>global</em> instance of the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code>.</p><p translation-result="on">在内部，所有静态方法在 <code><a href="api/core/testing/getTestBed" class="code-anchor">getTestBed</a>()</code> 函数返回的当前运行时间的 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 实例上都有对应的方法。</p><p translation-origin="off">Internally, all static methods cover methods of the current runtime <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> instance, which is also returned by the <code><a href="api/core/testing/getTestBed" class="code-anchor">getTestBed</a>()</code> function.</p><p translation-result="on">在 <code>BeforeEach()</code> 内调用 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 方法，以确保在运行每个单独测试时，都有崭新的开始。</p><p translation-origin="off">Call <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> methods <em>within</em> a <code>beforeEach()</code> to ensure a fresh start before each individual test.</p><p translation-result="on">这里列出了最重要的静态方法，以使用频率排序：</p><p translation-origin="off">Here are the most important static methods, in order of likely utility.</p><table><tbody><tr><th><p translation-result="on">方法</p><p translation-origin="off">Methods</p></th><th><p translation-result="on">说明</p><p translation-origin="off">Description</p></th></tr><tr><td style="vertical-align:top"><p> <code>configureTestingModule</code></p></td><td><p translation-result="on">测试垫片（<code>karma-test-shim</code>, <code>browser-test-shim</code>）创建了<a href="guide/testing">初始测试环境</a>和默认测试模块。 默认测试模块是使用基本声明和一些 Angular 服务替代品，它们是所有测试程序都需要的。</p><p translation-origin="off">The testing shims (<code>karma-test-shim</code>, <code>browser-test-shim</code>) establish the <a href="guide/testing">initial test environment</a> and a default testing module. The default testing module is configured with basic declaratives and some Angular service substitutes that every tester needs.</p><p translation-result="on">调用 <code>configureTestingModule</code> 来为一套特定的测试定义测试模块配置，添加和删除导入、（组件、指令和管道的）声明和服务提供商。</p><p translation-origin="off">Call <code>configureTestingModule</code> to refine the testing module configuration for a particular set of tests by adding and removing imports, declarations (of components, directives, and pipes), and providers.</p></td></tr><tr><td style="vertical-align:top"><p> <code>compileComponents</code></p></td><td><p translation-result="on">在配置好测试模块之后，异步编译它。 如果测试模块中的<em>任何一个</em>组件具有 <code><a href="api/core/Component#templateUrl" class="code-anchor">templateUrl</a></code> 或 <code><a href="api/core/Component#styleUrls" class="code-anchor">styleUrls</a></code>，那么你<strong>必须</strong>调用这个方法，因为获取组件的模板或样式文件必须是异步的。 参见<a href="guide/testing#compile-components">前面的讨论</a>。</p><p translation-origin="off">Compile the testing module asynchronously after you've finished configuring it. You <strong>must</strong> call this method if <em>any</em> of the testing module components have a <code><a href="api/core/Component#templateUrl" class="code-anchor">templateUrl</a></code> or <code><a href="api/core/Component#styleUrls" class="code-anchor">styleUrls</a></code> because fetching component template and style files is necessarily asynchronous. See <a href="guide/testing#compile-components">above</a>.</p><p translation-result="on">调用完 <code>compileComponents</code> 之后，<code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 的配置就会在当前测试期间被冻结。</p><p translation-origin="off">After calling <code>compileComponents</code>, the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> configuration is frozen for the duration of the current spec.</p></td></tr><tr><td style="vertical-align:top"><p> <code>createComponent<t></t></code></p></td><td><p translation-result="on">基于当前 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 的配置创建一个类型为 T 的组件实例。 一旦调用，<code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 的配置就会在当前测试期间被冻结。</p><p translation-origin="off">Create an instance of a component of type <code>T</code> based on the current <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> configuration. After calling <code>compileComponent</code>, the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> configuration is frozen for the duration of the current spec.</p></td></tr><tr><td style="vertical-align:top"><p> <code>overrideModule</code></p></td><td><p translation-result="on">替换指定的 <code><a href="api/core/NgModule" class="code-anchor">NgModule</a></code> 的元数据。回想一下，模块可以导入其他模块。 <code>overrideModule</code> 方法可以深入到当前测试模块深处，修改其中一个内部模块。</p><p translation-origin="off">Replace metadata for the given <code><a href="api/core/NgModule" class="code-anchor">NgModule</a></code>. Recall that modules can import other modules. The <code>overrideModule</code> method can reach deeply into the current testing module to modify one of these inner modules.</p></td></tr><tr><td style="vertical-align:top"><p> <code>overrideComponent</code></p></td><td><p translation-result="on">替换指定组件类的元数据，该组件类可能嵌套在一个很深的内部模块中。</p><p translation-origin="off">Replace metadata for the given component class, which could be nested deeply within an inner module.</p></td></tr><tr><td style="vertical-align:top"><p> <code>overrideDirective</code></p></td><td><p translation-result="on">替换指定指令类的元数据，该指令可能嵌套在一个很深的内部模块中。</p><p translation-origin="off">Replace metadata for the given directive class, which could be nested deeply within an inner module.</p></td></tr><tr><td style="vertical-align:top"><p> <code>overridePipe</code></p></td><td><p translation-result="on">替换指定管道类的元数据，该管道可能嵌套在一个很深的内部模块中。</p><p translation-origin="off">Replace metadata for the given pipe class, which could be nested deeply within an inner module.</p></td></tr><tr><td style="vertical-align:top"><p><a id="testbed-inject"></a></p><p> <code>inject</code></p></td><td><p translation-result="on">从当前 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 注入器获取一个服务。</p><p translation-origin="off">Retrieve a service from the current <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> injector.</p><p translation-result="on"> <code>inject</code> 函数通常都能胜任这项工作，但是如果它没法提供该服务时就会抛出一个异常。</p><p translation-origin="off">The <code>inject</code> function is often adequate for this purpose. But <code>inject</code> throws an error if it can't provide the service.</p><p translation-result="on">如果该服务是可选的呢？</p><p translation-origin="off">What if the service is optional?</p><p translation-result="on"> <code>TestBed.inject()</code> 方法可以接受可选的第二参数，当 Angular 找不到指定的服务提供商时，就会返回该对象（下面这个例子中是 <code>null</code> ）：</p><p translation-origin="off">The <code>TestBed.inject()</code> method takes an optional second parameter, the object to return if Angular can't find the provider (<code>null</code> in this example):</p><p><code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="testbed-get-w-null" header="app/demo/demo.testbed.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">service = TestBed.inject(NotProvided, null); // service is null</div><header class="ng-star-inserted">app/demo/demo.testbed.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/demo/demo.testbed.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">service </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">inject</span><span class="pun">(</span><span class="typ">NotProvided</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">);</span><span class="pln"> </span><span class="com">// service is null</span></code>
    </pre></aio-code></code-example></p><p translation-result="on">调用了 <code>TestBed.inject</code> 之后然后通过调用，<code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 的配置就会在当前测试期间被冻结。</p><p translation-origin="off">After calling <code>TestBed.inject</code>, the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> configuration is frozen for the duration of the current spec.</p></td></tr><tr><td style="vertical-align:top"><p><a id="testbed-initTestEnvironment"></a></p><p> <code>initTestEnvironment</code></p></td><td><p translation-result="on">为整套测试的运行初始化测试环境。</p><p translation-origin="off">Initialize the testing environment for the entire test run.</p><p translation-result="on">测试垫片(<code>karma-test-shim</code>, <code>browser-test-shim</code>)会为你调用它，所以你很少需要自己调用它。</p><p translation-origin="off">The testing shims (<code>karma-test-shim</code>, <code>browser-test-shim</code>) call it for you so there is rarely a reason for you to call it yourself.</p><p translation-result="on">这个方法只能被调用<strong>一次</strong>。如果确实需要在测试程序运行期间改变这个默认设置，那么先调用 <code>resetTestEnvironment</code>。</p><p translation-origin="off">You may call this method <em>exactly once</em>. If you must change this default in the middle of your test run, call <code>resetTestEnvironment</code> first.</p><p translation-result="on">指定 Angular 编译器工厂，<code><a href="api/core/PlatformRef" class="code-anchor">PlatformRef</a></code>，和默认 Angular 测试模块。 以 <code>@angular/platform-&lt;platform_name&gt;/testing/&lt;platform_name&gt;</code> 的形式提供非浏览器平台的替代品。</p><p translation-origin="off">Specify the Angular compiler factory, a <code><a href="api/core/PlatformRef" class="code-anchor">PlatformRef</a></code>, and a default Angular testing module. Alternatives for non-browser platforms are available in the general form <code>@angular/platform-&lt;platform_name&gt;/testing/&lt;platform_name&gt;</code>.</p></td></tr><tr><td style="vertical-align:top"><p> <code>resetTestEnvironment</code></p></td><td><p translation-result="on">重设初始测试环境，包括默认测试模块在内。</p><p translation-origin="off">Reset the initial test environment, including the default testing module.</p></td></tr></tbody></table><p translation-result="on">少数 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 实例方法没有对应的静态方法。它们很少被使用。</p><p translation-origin="off">A few of the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> instance methods are not covered by static <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> <em>class</em> methods. These are rarely needed.</p><a id="component-fixture-api-summary"></a><h4 id="the-componentfixture" translation-result="on"><code><a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a></code> 类<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-componentfixture"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="the-componentfixture">The <em>ComponentFixture</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#the-componentfixture"><i class="material-icons">link</i></a></h4><p translation-result="on"><code>TestBed.createComponent&lt;T&gt;</code> 会创建一个组件 <code>T</code> 的实例，并为该组件返回一个强类型的 <code><a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a></code>。</p><p translation-origin="off">The <code>TestBed.createComponent&lt;T&gt;</code> creates an instance of the component <code>T</code> and returns a strongly typed <code><a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a></code> for that component.</p><p translation-result="on"><code><a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a></code> 的属性和方法提供了对组件、它的 DOM 和它的 Angular 环境方面的访问。</p><p translation-origin="off">The <code><a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a></code> properties and methods provide access to the component, its DOM representation, and aspects of its Angular environment.</p><a id="component-fixture-properties"></a><h4 id="componentfixture-properties" translation-result="on"><code><a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a></code> 的属性<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#componentfixture-properties"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="componentfixture-properties"><em>ComponentFixture</em> properties<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#componentfixture-properties"><i class="material-icons">link</i></a></h4><p translation-result="on">下面是对测试最重要的属性，以使用频率排序：</p><p translation-origin="off">Here are the most important properties for testers, in order of likely utility.</p><table><tbody><tr><th><p translation-result="on">属性</p><p translation-origin="off">Properties</p></th><th><p translation-result="on">说明</p><p translation-origin="off">Description</p></th></tr><tr><td style="vertical-align:top"><p> <code>componentInstance</code></p></td><td><p translation-result="on">被 <code>TestBed.createComponent</code> 创建的组件类实例。</p><p translation-origin="off">The instance of the component class created by <code>TestBed.createComponent</code>.</p></td></tr><tr><td style="vertical-align:top"><p> <code><a href="api/core/testing/ComponentFixture#debugElement" class="code-anchor">debugElement</a></code></p></td><td><p translation-result="on">与组件根元素关联的 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code>。</p><p translation-origin="off">The <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> associated with the root element of the component.</p><p translation-result="on"> <code><a href="api/core/testing/ComponentFixture#debugElement" class="code-anchor">debugElement</a></code> 提供了在测试和调试期间深入探查组件及其 DOM 元素的功能。 它对于测试者是一个极其重要的属性。它的大多数主要成员在<a href="guide/testing#debug-element-details">后面</a>都有讲解。</p><p translation-origin="off">The <code><a href="api/core/testing/ComponentFixture#debugElement" class="code-anchor">debugElement</a></code> provides insight into the component and its DOM element during test and debugging. It's a critical property for testers. The most interesting members are covered <a href="guide/testing#debug-element-details">below</a>.</p></td></tr><tr><td style="vertical-align:top"><p> <code>nativeElement</code></p></td><td><p translation-result="on">组件的原生根 DOM 元素。</p><p translation-origin="off">The native DOM element at the root of the component.</p></td></tr><tr><td style="vertical-align:top"><p> <code>changeDetectorRef</code></p></td><td><p translation-result="on">组件的 <code><a href="api/core/ChangeDetectorRef" class="code-anchor">ChangeDetectorRef</a></code>。</p><p translation-origin="off">The <code><a href="api/core/ChangeDetectorRef" class="code-anchor">ChangeDetectorRef</a></code> for the component.</p><p translation-result="on">在测试一个拥有 <code><a href="api/core/ChangeDetectionStrategy#OnPush" class="code-anchor">ChangeDetectionStrategy.OnPush</a></code> 的组件，或者在组件的变化测试在你的程序控制下时，<code><a href="api/core/ChangeDetectorRef" class="code-anchor">ChangeDetectorRef</a></code> 是最重要的。</p><p translation-origin="off">The <code><a href="api/core/ChangeDetectorRef" class="code-anchor">ChangeDetectorRef</a></code> is most valuable when testing a component that has the <code><a href="api/core/ChangeDetectionStrategy#OnPush" class="code-anchor">ChangeDetectionStrategy.OnPush</a></code> method or the component's change detection is under your programmatic control.</p></td></tr></tbody></table><a id="component-fixture-methods"></a><h4 id="componentfixture-methods" translation-result="on"><code><a href="api/core/testing/ComponentFixture" class="code-anchor">ComponentFixture</a></code> 的方法<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#componentfixture-methods"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="componentfixture-methods"><em>ComponentFixture</em> methods<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#componentfixture-methods"><i class="material-icons">link</i></a></h4><p translation-result="on"><strong>fixture</strong> 方法使 Angular 对组件树执行某些任务。 在触发 Angular 行为来模拟的用户行为时，调用这些方法。</p><p translation-origin="off">The <em>fixture</em> methods cause Angular to perform certain tasks on the component tree. Call these method to trigger Angular behavior in response to simulated user action.</p><p translation-result="on">下面是对测试最有用的方法。</p><p translation-origin="off">Here are the most useful methods for testers.</p><table><tbody><tr><th><p translation-result="on">方法</p><p translation-origin="off">Methods</p></th><th><p translation-result="on">说明</p><p translation-origin="off">Description</p></th></tr><tr><td style="vertical-align:top"><p> <code>detectChanges</code></p></td><td><p translation-result="on">为组件触发一轮变化检查。</p><p translation-origin="off">Trigger a change detection cycle for the component.</p><p translation-result="on">调用它来初始化组件（它调用 <code>ngOnInit</code>）。或者在你的测试代码改变了组件的数据绑定属性值后调用它。 Angular 不能检测到你已经改变了 <code>personComponent.name</code> 属性，也不会更新 <code>name</code> 的绑定，直到你调用了 <code>detectChanges</code>。</p><p translation-origin="off">Call it to initialize the component (it calls <code>ngOnInit</code>) and after your test code, change the component's data bound property values. Angular can't see that you've changed <code>personComponent.name</code> and won't update the <code>name</code> binding until you call <code>detectChanges</code>.</p><p translation-result="on">之后，运行 <code>checkNoChanges</code>，来确认没有循环更新，除非它被这样调用：<code>detectChanges(false)</code>。</p><p translation-origin="off">Runs <code>checkNoChanges</code> afterwards to confirm that there are no circular updates unless called as <code>detectChanges(false)</code>;</p></td></tr><tr><td style="vertical-align:top"><p> <code>autoDetectChanges</code></p></td><td><p translation-result="on">如果你希望这个夹具自动检测变更，就把这个设置为 <code>true</code>。</p><p translation-origin="off">Set this to <code>true</code> when you want the fixture to detect changes automatically.</p><p translation-result="on">当自动检测打开时，测试 fixture 监听 <strong>zone</strong> 事件，并调用 <code>detectChanges</code>。 当你的测试代码直接修改了组件属性值时，你还是要调用 <code>fixture.detectChanges</code> 来触发数据绑定更新。</p><p translation-origin="off">When autodetect is <code>true</code>, the test fixture calls <code>detectChanges</code> immediately after creating the component. Then it listens for pertinent zone events and calls <code>detectChanges</code> accordingly. When your test code modifies component property values directly, you probably still have to call <code>fixture.detectChanges</code> to trigger data binding updates.</p><p translation-result="on">默认值是 <code>false</code>，喜欢对测试行为进行精细控制的测试者一般保持它为 <code>false</code>。</p><p translation-origin="off">The default is <code>false</code>. Testers who prefer fine control over test behavior tend to keep it <code>false</code>.</p></td></tr><tr><td style="vertical-align:top"><p> <code>checkNoChanges</code></p></td><td><p translation-result="on">运行一次变更检测来确认没有待处理的变化。如果有未处理的变化，它将抛出一个错误。</p><p translation-origin="off">Do a change detection run to make sure there are no pending changes. Throws an exceptions if there are.</p></td></tr><tr><td style="vertical-align:top"><p> <code>isStable</code></p></td><td><p translation-result="on">如果 fixture 当前是<strong>稳定的</strong>，则返回 <code>true</code>。 如果有异步任务没有完成，则返回 <code>false</code>。</p><p translation-origin="off">If the fixture is currently <em>stable</em>, returns <code>true</code>. If there are async tasks that have not completed, returns <code>false</code>.</p></td></tr><tr><td style="vertical-align:top"><p> <code>whenStable</code></p></td><td><p translation-result="on">返回一个承诺，在 fixture 稳定时解析。</p><p translation-origin="off">Returns a promise that resolves when the fixture is stable.</p><p translation-result="on">要想在完成了异步活动或异步变更检测之后再继续测试，可以对那个承诺对象进行挂钩。 参见 <a href="guide/testing#when-stable">前面</a>。</p><p translation-origin="off">To resume testing after completion of asynchronous activity or asynchronous change detection, hook that promise. See <a href="guide/testing#when-stable">above</a>.</p></td></tr><tr><td style="vertical-align:top"><p> <code>destroy</code></p></td><td><p translation-result="on">触发组件的销毁。</p><p translation-origin="off">Trigger component destruction.</p></td></tr></tbody></table><a id="debug-element-details"></a><h4 id="debugelement-1"><em>DebugElement</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#debugelement-1"><i class="material-icons">link</i></a></h4><p translation-result="on"><code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 提供了对组件的 DOM 的访问。</p><p translation-origin="off">The <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> provides crucial insights into the component's DOM representation.</p><p translation-result="on"><code>fixture.debugElement</code> 返回测试根组件的 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code>，通过它你可以访问（查询）fixture 的整个元素和组件子树。</p><p translation-origin="off">From the test root component's <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> returned by <code>fixture.debugElement</code>, you can walk (and query) the fixture's entire element and component subtrees.</p><p translation-result="on">下面是 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 最有用的成员，以使用频率排序。</p><p translation-origin="off">Here are the most useful <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> members for testers, in approximate order of utility:</p><table><tbody><tr><th><p translation-result="on">成员</p><p translation-origin="off">Member</p></th><th><p translation-result="on">说明</p><p translation-origin="off">Description</p></th></tr><tr><td style="vertical-align:top"><p> <code>nativeElement</code></p></td><td><p translation-result="on">与浏览器中 DOM 元素对应（WebWorkers 时，值为 null）。</p><p translation-origin="off">The corresponding DOM element in the browser (null for WebWorkers).</p></td></tr><tr><td style="vertical-align:top"><p> <code><a href="api/animations/query" class="code-anchor">query</a></code></p></td><td><p translation-result="on">调用 <code><a href="api/animations/query" class="code-anchor">query</a>(predicate: <a href="api/core/Predicate" class="code-anchor">Predicate</a>&lt;<a href="api/core/DebugElement" class="code-anchor">DebugElement</a>&gt;)</code> 会在子树的任意深度中查找并返回能和<a href="guide/testing#query-predicate">谓词函数</a>匹配的第一个 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code>。</p><p translation-origin="off">Calling <code><a href="api/animations/query" class="code-anchor">query</a>(predicate: <a href="api/core/Predicate" class="code-anchor">Predicate</a>&lt;<a href="api/core/DebugElement" class="code-anchor">DebugElement</a>&gt;)</code> returns the first <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> that matches the <a href="guide/testing#query-predicate">predicate</a> at any depth in the subtree.</p></td></tr><tr><td style="vertical-align:top"><p> <code>queryAll</code></p></td><td><p translation-result="on">调用 <code>queryAll(predicate: <a href="api/core/Predicate" class="code-anchor">Predicate</a>&lt;<a href="api/core/DebugElement" class="code-anchor">DebugElement</a>&gt;)</code> 会在子树的任意深度中查找能和<a href="guide/testing#query-predicate">谓词函数</a>匹配的所有 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code>。</p><p translation-origin="off">Calling <code>queryAll(predicate: <a href="api/core/Predicate" class="code-anchor">Predicate</a>&lt;<a href="api/core/DebugElement" class="code-anchor">DebugElement</a>&gt;)</code> returns all <code>DebugElements</code> that matches the <a href="guide/testing#query-predicate">predicate</a> at any depth in subtree.</p></td></tr><tr><td style="vertical-align:top"><p> <code>injector</code></p></td><td><p translation-result="on">宿主依赖注入器。 比如，根元素的组件实例注入器。</p><p translation-origin="off">The host dependency injector. For example, the root element's component instance injector.</p></td></tr><tr><td style="vertical-align:top"><p> <code>componentInstance</code></p></td><td><p translation-result="on">元素自己的组件实例（如果有）。</p><p translation-origin="off">The element's own component instance, if it has one.</p></td></tr><tr><td style="vertical-align:top"><p> <code>context</code></p></td><td><p translation-result="on">为元素提供父级上下文的对象。 通常是控制该元素的祖级组件实例。</p><p translation-origin="off">An object that provides parent context for this element. Often an ancestor component instance that governs this element.</p><p translation-result="on">当一个元素被 <code>*<a href="api/common/NgForOf" class="code-anchor">ngFor</a></code> 重复，它的上下文为 <code>NgForRow</code>，它的 <code>$implicit</code> 属性值是该行的实例值。 比如，<code>*<a href="api/common/NgForOf" class="code-anchor">ngFor</a>="let hero of heroes"</code> 里的 <code>hero</code>。</p><p translation-origin="off">When an element is repeated within <code>*<a href="api/common/NgForOf" class="code-anchor">ngFor</a></code>, the context is an <code>NgForRow</code> whose <code>$implicit</code> property is the value of the row instance value. For example, the <code>hero</code> in <code>*<a href="api/common/NgForOf" class="code-anchor">ngFor</a>="let hero of heroes"</code>.</p></td></tr><tr><td style="vertical-align:top"><p> <code>children</code></p></td><td><p translation-result="on"> <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 的直接子元素。可以通过继续深入 <code>children</code> 来遍历这棵树。</p><p translation-origin="off">The immediate <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> children. Walk the tree by descending through <code>children</code>.</p><div class="alert is-helpful"><p translation-result="on"> <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 还有 <code><a href="api/core/DebugElement#childNodes" class="code-anchor">childNodes</a></code>，即 <code><a href="api/core/DebugNode" class="code-anchor">DebugNode</a></code> 对象列表。 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 从 <code><a href="api/core/DebugNode" class="code-anchor">DebugNode</a></code> 对象衍生，而且通常节点（node）比元素多。测试者通常忽略赤裸节点。</p><p translation-origin="off"> <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> also has <code><a href="api/core/DebugElement#childNodes" class="code-anchor">childNodes</a></code>, a list of <code><a href="api/core/DebugNode" class="code-anchor">DebugNode</a></code> objects. <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> derives from <code><a href="api/core/DebugNode" class="code-anchor">DebugNode</a></code> objects and there are often more nodes than elements. Testers can usually ignore plain nodes.</p></div></td></tr><tr><td style="vertical-align:top"><p> <code>parent</code></p></td><td><p translation-result="on"> <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 的父级。如果 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 是根元素，<code>parent</code> 为 null。</p><p translation-origin="off">The <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> parent. Null if this is the root element.</p></td></tr><tr><td style="vertical-align:top"><p> <code>name</code></p></td><td><p translation-result="on">元素的标签名字，如果它是一个元素的话。</p><p translation-origin="off">The element tag name, if it is an element.</p></td></tr><tr><td style="vertical-align:top"><p> <code>triggerEventHandler</code></p></td><td><p translation-result="on">如果在该元素的 <code><a href="api/core/DebugNode#listeners" class="code-anchor">listeners</a></code> 集合中有相应的监听器，就根据名字触发这个事件。 第二个参数是该处理器函数所需的<em>事件对象</em>。参见<a href="guide/testing#trigger-event-handler">前面</a>。</p><p translation-origin="off">Triggers the event by its name if there is a corresponding listener in the element's <code><a href="api/core/DebugNode#listeners" class="code-anchor">listeners</a></code> collection. The second parameter is the <em>event object</em> expected by the handler. See <a href="guide/testing#trigger-event-handler">above</a>.</p><p translation-result="on">如果事件缺乏监听器，或者有其它问题，考虑调用 <code>nativeElement.dispatchEvent(eventObject)</code>。</p><p translation-origin="off">If the event lacks a listener or there's some other problem, consider calling <code>nativeElement.dispatchEvent(eventObject)</code>.</p></td></tr><tr><td style="vertical-align:top"><p> <code><a href="api/core/DebugNode#listeners" class="code-anchor">listeners</a></code></p></td><td><p translation-result="on">元素的 <code>@<a href="api/core/Output" class="code-anchor">Output</a></code> 属性以及/或者元素的事件属性所附带的回调函数。</p><p translation-origin="off">The callbacks attached to the component's <code>@<a href="api/core/Output" class="code-anchor">Output</a></code> properties and/or the element's event properties.</p></td></tr><tr><td style="vertical-align:top"><p> <code><a href="api/core/DebugNode#providerTokens" class="code-anchor">providerTokens</a></code></p></td><td><p translation-result="on">组件注入器的查询令牌。 包括组件自己的令牌和组件的 <code>providers</code> 元数据中列出来的令牌。</p><p translation-origin="off">This component's injector lookup tokens. Includes the component itself plus the tokens that the component lists in its <code>providers</code> metadata.</p></td></tr><tr><td style="vertical-align:top"><p> <code>source</code></p></td><td><p translation-result="on">source 是在源组件模板中查询这个元素的处所。</p><p translation-origin="off">Where to find this element in the source component template.</p></td></tr><tr><td style="vertical-align:top"><p> <code><a href="api/core/DebugNode#references" class="code-anchor">references</a></code></p></td><td><p translation-result="on">与模板本地变量（比如 <code>#foo</code>）关联的词典对象，关键字与本地变量名字配对。</p><p translation-origin="off">Dictionary of objects associated with template local variables (e.g. <code>#foo</code>), keyed by the local variable name.</p></td></tr></tbody></table><a id="query-predicate"></a><p translation-result="on"><code>DebugElement.query(predicate)</code> 和 <code>DebugElement.queryAll(predicate)</code> 方法接受一个条件方法， 它过滤源元素的子树，返回匹配的 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code>。</p><p translation-origin="off">The <code>DebugElement.query(predicate)</code> and <code>DebugElement.queryAll(predicate)</code> methods take a predicate that filters the source element's subtree for matching <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code>.</p><p translation-result="on">这个条件方法是任何接受一个 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> 并返回真值的方法。 下面的例子查询所有拥有名为 <code>content</code> 的模块本地变量的所有 <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code>：</p><p translation-origin="off">The predicate is any method that takes a <code><a href="api/core/DebugElement" class="code-anchor">DebugElement</a></code> and returns a <em>truthy</em> value. The following example finds all <code>DebugElements</code> with a reference to a template local variable named "content":</p><code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="custom-predicate" header="app/demo/demo.testbed.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">// Filter for DebugElements with a #content reference const contentRefs = el.queryAll( de =&gt; de.references['content']);</div><header class="ng-star-inserted">app/demo/demo.testbed.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/demo/demo.testbed.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// Filter for DebugElements with a #content reference</span><span class="pln">
</span><span class="kwd">const</span><span class="pln"> contentRefs </span><span class="pun">=</span><span class="pln"> el</span><span class="pun">.</span><span class="pln">queryAll</span><span class="pun">(</span><span class="pln"> de </span><span class="pun">=&gt;</span><span class="pln"> de</span><span class="pun">.</span><span class="pln">references</span><span class="pun">[</span><span class="str">'content'</span><span class="pun">]);</span></code>
    </pre></aio-code></code-example><p translation-result="on">Angular 的 <code><a href="api/platform-browser/By" class="code-anchor">By</a></code> 类为常用条件方法提供了三个静态方法：</p><p translation-origin="off">The Angular <code><a href="api/platform-browser/By" class="code-anchor">By</a></code> class has three static methods for common predicates:</p><ul><li><p translation-result="on"> <code>By.all</code> - 返回所有元素</p><p translation-origin="off"><code>By.all</code> - return all elements.</p></li><li><p translation-result="on"> <code>By.css(selector)</code> - 返回符合 CSS 选择器的元素。</p><p translation-origin="off"><code>By.css(selector)</code> - return elements with matching CSS selectors.</p></li><li><p translation-result="on"> <code>By.directive(directive)</code> - 返回 Angular 能匹配一个指令类实例的所有元素。</p><p translation-origin="off"><code>By.directive(directive)</code> - return elements that Angular matched to an instance of the directive class.</p></li></ul><code-example path="testing/src/app/hero/hero-list.component.spec.ts" region="by" header="app/hero/hero-list.component.spec.ts" ng-version="9.0.0-rc.11"><div style="display:none">// Can find <a href="api/core/DebugElement" class="code-anchor">DebugElement</a> either by css selector or by directive const h2 = fixture.debugElement.query(By.css('h2')); const directive = fixture.debugElement.query(By.directive(HighlightDirective));</div><header class="ng-star-inserted">app/hero/hero-list.component.spec.ts</header><aio-code class="headed-code"><pre class="lang- prettyprint">      <button title="Copy code snippet" class="material-icons copy-button no-print ng-star-inserted" aria-label="Copy code snippet from app/hero/hero-list.component.spec.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// Can find </span><a href="api/core/DebugElement" class="code-anchor"><span class="com">DebugElement</span></a><span class="com"> either by css selector or by directive</span><span class="pln">
</span><span class="kwd">const</span><span class="pln"> h2        </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">.</span><span class="pln">query</span><span class="pun">(</span><span class="typ">By</span><span class="pun">.</span><span class="pln">css</span><span class="pun">(</span><span class="str">'h2'</span><span class="pun">));</span><span class="pln">
</span><span class="kwd">const</span><span class="pln"> directive </span><span class="pun">=</span><span class="pln"> fixture</span><span class="pun">.</span><span class="pln">debugElement</span><span class="pun">.</span><span class="pln">query</span><span class="pun">(</span><span class="typ">By</span><span class="pun">.</span><span class="pln">directive</span><span class="pun">(</span><span class="typ">HighlightDirective</span><span class="pun">));</span></code>
    </pre></aio-code></code-example><hr><a id="faq"></a><h2 id="frequently-asked-questions" translation-result="on">常见问题<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#frequently-asked-questions"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="frequently-asked-questions">Frequently Asked Questions<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#frequently-asked-questions"><i class="material-icons">link</i></a></h2><a id="q-spec-file-location"></a><h4 id="why-put-spec-file-next-to-the-file-it-tests" translation-result="on">为什么要把测试文件和被测文件放在一起？<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#why-put-spec-file-next-to-the-file-it-tests"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="why-put-spec-file-next-to-the-file-it-tests">Why put spec file next to the file it tests?<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#why-put-spec-file-next-to-the-file-it-tests"><i class="material-icons">link</i></a></h4><p translation-result="on">将单元测试的 spec 配置文件放到与应用程序源代码文件所在的同一个文件夹中是个好主意，因为：</p><p translation-origin="off">It's a good idea to put unit test spec files in the same folder as the application source code files that they test:</p><ul><li><p translation-result="on">这样的测试程序很容易被找到</p><p translation-origin="off">Such tests are easy to find.</p></li><li><p translation-result="on">你可以一眼看出应用程序的哪些部分缺乏测试程序。</p><p translation-origin="off">You see at a glance if a part of your application lacks tests.</p></li><li><p translation-result="on">临近的测试程序可以展示代码是如何在上下文中工作的</p><p translation-origin="off">Nearby tests can reveal how a part works in context.</p></li><li><p translation-result="on">当你移动代码（无可避免）时，你记得一起移动测试程序</p><p translation-origin="off">When you move the source (inevitable), you remember to move the test.</p></li><li><p translation-result="on">当你重命名源代码文件（无可避免），你记得重命名测试程序文件。</p><p translation-origin="off">When you rename the source file (inevitable), you remember to rename the test file.</p></li></ul><hr><a id="q-specs-in-test-folder"></a><h4 id="when-would-i-put-specs-in-a-test-folder" translation-result="on">什么时候我该把测试文件放进单独的 <code>test</code> 文件夹中？<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#when-would-i-put-specs-in-a-test-folder"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="when-would-i-put-specs-in-a-test-folder">When would I put specs in a test folder?<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#when-would-i-put-specs-in-a-test-folder"><i class="material-icons">link</i></a></h4><p translation-result="on">应用程序的整合测试 spec 文件可以测试横跨多个目录和模块的多个部分之间的互动。 它们不属于任何部分，很自然，没有特别的地方存放它们。</p><p translation-origin="off">Application integration specs can test the interactions of multiple parts spread across folders and modules. They don't really belong to any part in particular, so they don't have a natural home next to any one file.</p><p translation-result="on">通常，在 <code>test</code> 目录中为它们创建一个合适的目录比较好。</p><p translation-origin="off">It's often better to create an appropriate folder for them in the <code>tests</code> directory.</p><p translation-result="on">当然，<strong>测试助手对象</strong>的测试 spec 文件也属于 <code>test</code> 目录，与它们对应的助手文件相邻。</p><p translation-origin="off">Of course specs that test the test helpers belong in the <code>test</code> folder, next to their corresponding helper files.</p><a id="q-e2e"></a><h4 id="why-not-rely-on-e2e-tests-of-dom-integration" translation-result="on">为什么不依赖 E2E 测试来保障 DOM 集成后的正确性？<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#why-not-rely-on-e2e-tests-of-dom-integration"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="why-not-rely-on-e2e-tests-of-dom-integration">Why not rely on E2E tests of DOM integration?<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#why-not-rely-on-e2e-tests-of-dom-integration"><i class="material-icons">link</i></a></h4><p translation-result="on">本指南中讲的组件 DOM 测试通常需要大量的准备工作以及高级技巧，不像<a href="guide/testing#component-class-testing">只针对类的测试</a>那样简单。</p><p translation-origin="off">The component DOM tests described in this guide often require extensive setup and advanced techniques whereas the <a href="guide/testing#component-class-testing">unit tests</a> are comparatively simple.</p><h4 id="why-not-defer-dom-integration-tests-to-end-to-end-e2e-testing" translation-result="on">为什么不等到端到端（E2E）测试阶段再对 DOM 进行集成测试呢？<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#why-not-defer-dom-integration-tests-to-end-to-end-e2e-testing"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="why-not-defer-dom-integration-tests-to-end-to-end-e2e-testing">Why not defer DOM integration tests to end-to-end (E2E) testing?<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/testing#why-not-defer-dom-integration-tests-to-end-to-end-e2e-testing"><i class="material-icons">link</i></a></h4><p translation-result="on">E2E 测试对于整个系统的高层验证非常好用。 但是它们没法给你像单元测试这样全面的测试覆盖率。</p><p translation-origin="off">E2E tests are great for high-level validation of the entire system. But they can't give you the comprehensive test coverage that you'd expect from unit tests.</p><p translation-result="on">E2E 测试很难写，并且执行性能也赶不上单元测试。 它们很容易被破坏，而且经常是因为某些远离故障点的修改或不当行为而导致的。</p><p translation-origin="off">E2E tests are difficult to write and perform poorly compared to unit tests. They break easily, often due to changes or misbehavior far removed from the site of breakage.</p><p translation-result="on">当出错时，E2E 测试不能轻松揭露你的组件出了什么问题， 比如丢失或错误的数据、网络失去连接或远端服务器挂了。</p><p translation-origin="off">E2E tests can't easily reveal how your components behave when things go wrong, such as missing or bad data, lost connectivity, and remote service failures.</p><p translation-result="on">如果 E2E 的测试对象要更新数据库、发送发票或收取信用卡，就需要一些特殊的技巧和后门来防止远程资源被意外破坏。 它甚至可能都难以导航到你要测试的组件。</p><p translation-origin="off">E2E tests for apps that update a database, send an invoice, or charge a credit card require special tricks and back-doors to prevent accidental corruption of remote resources. It can even be hard to navigate to the component you want to test.</p><p translation-result="on">由于存在这么多障碍，你应该尽可能使用单元测试技术来测试 DOM 交互。</p><p translation-origin="off">Because of these many obstacles, you should test DOM interaction with unit testing techniques as much as possible.</p></div></div></aio-doc-viewer></main></mat-sidenav-content></mat-sidenav-container><div class="toc-container no-print ng-star-inserted"><aio-lazy-ce selector="aio-toc"><aio-toc ng-version="9.0.0-rc.11"><div class="toc-inner no-print collapsed ng-star-inserted"><ul class="toc-list"><li class="h1 ng-star-inserted active" title="测试"><a href="guide/testing#testing">测试</a></li><li class="h2 ng-star-inserted" title="建立环境"><a href="guide/testing#setup">建立环境</a></li><li class="h2 ng-star-inserted" title="建立持续集成环境"><a href="guide/testing#set-up-continuous-integration">建立持续集成环境</a></li><li class="h3 ng-star-inserted" title="为 Circle CI 配置项目"><a href="guide/testing#configure-project-for-circle-ci">为 Circle CI 配置项目</a></li><li class="h3 ng-star-inserted" title="为 Travis CI 配置项目"><a href="guide/testing#configure-project-for-travis-ci">为 Travis CI 配置项目</a></li><li class="h3 ng-star-inserted" title="为在 Chrome 中运行 CI 测试而配置 CLI"><a href="guide/testing#configure-cli-for-ci-testing-in-chrome">为在 Chrome 中运行 CI 测试而配置 CLI</a></li><li class="h2 ng-star-inserted" title="启用代码覆盖率报告"><a href="guide/testing#enable-code-coverage-reports">启用代码覆盖率报告</a></li><li class="h3 ng-star-inserted" title="代码覆盖率实施"><a href="guide/testing#code-coverage-enforcement">代码覆盖率实施</a></li><li class="h2 ng-star-inserted" title="对服务的测试"><a href="guide/testing#service-tests">对服务的测试</a></li><li class="h2 ng-star-inserted" title="组件测试基础"><a href="guide/testing#component-test-basics">组件测试基础</a></li><li class="h3 ng-star-inserted" title="单独测试组件类"><a href="guide/testing#component-class-testing">单独测试组件类</a></li><li class="h3 ng-star-inserted" title="组件 DOM 的测试"><a href="guide/testing#component-dom-testing">组件 DOM 的测试</a></li><li class="h2 ng-star-inserted" title="组件测试场景"><a href="guide/testing#component-test-scenarios">组件测试场景</a></li><li class="h3 ng-star-inserted" title="组件绑定"><a href="guide/testing#component-binding">组件绑定</a></li><li class="h3 ng-star-inserted" title="带有外部文件的组件"><a href="guide/testing#component-with-external-files">带有外部文件的组件</a></li><li class="h3 ng-star-inserted" title="带依赖的组件"><a href="guide/testing#component-with-a-dependency">带依赖的组件</a></li><li class="h3 ng-star-inserted" title="带有异步服务的组件"><a href="guide/testing#component-with-async-service">带有异步服务的组件</a></li><li class="h3 ng-star-inserted" title="组件的弹珠测试"><a href="guide/testing#component-marble-tests">组件的弹珠测试</a></li><li class="h3 ng-star-inserted" title="带有输入输出参数的组件"><a href="guide/testing#component-with-inputs-and-outputs">带有输入输出参数的组件</a></li><li class="h3 ng-star-inserted" title="位于测试宿主中的组件"><a href="guide/testing#component-inside-a-test-host">位于测试宿主中的组件</a></li><li class="h3 ng-star-inserted" title="路由组件"><a href="guide/testing#routing-component">路由组件</a></li><li class="h3 ng-star-inserted" title="路由目标组件"><a href="guide/testing#routed-components">路由目标组件</a></li><li class="h3 ng-star-inserted" title="对嵌套组件的测试"><a href="guide/testing#nested-component-tests">对嵌套组件的测试</a></li><li class="h3 ng-star-inserted" title="带有 RouterLink 的组件"><a href="guide/testing#components-with-routerlink">带有 <code>RouterLink</code> 的组件</a></li><li class="h3 ng-star-inserted" title="使用页面（page）对象"><a href="guide/testing#use-a-page-object">使用页面（page）对象</a></li><li class="h3 ng-star-inserted" title="调用 compileComponents()"><a href="guide/testing#calling-compilecomponents">调用 <code>compileComponents()</code></a></li><li class="h3 ng-star-inserted" title="准备模块的 imports"><a href="guide/testing#setup-with-module-imports">准备模块的 <code>imports</code></a></li><li class="h3 ng-star-inserted" title="改写组件的服务提供商"><a href="guide/testing#override-component-providers">改写组件的服务提供商</a></li><li class="h2 ng-star-inserted" title="属性型指令的测试"><a href="guide/testing#attribute-directive-testing">属性型指令的测试</a></li><li class="h2 ng-star-inserted" title="管道测试"><a href="guide/testing#pipe-testing">管道测试</a></li><li class="h2 ng-star-inserted" title="测试程序的调试"><a href="guide/testing#test-debugging">测试程序的调试</a></li><li class="h2 ng-star-inserted" title="测试工具 API"><a href="guide/testing#testing-utility-apis">测试工具 API</a></li><li class="h2 ng-star-inserted" title="常见问题"><a href="guide/testing#frequently-asked-questions">常见问题</a></li></ul></div></aio-toc></aio-lazy-ce></div><footer class="no-print"><aio-footer><div class="grid-fluid"><div class="footer-block ng-star-inserted"><h3>资源</h3><ul><li class="ng-star-inserted"><a class="link" href="about" title="Angular 贡献者。">关于</a></li><li class="ng-star-inserted"><a class="link" href="resources" title="网络上的 Angular 工具、培训、博客等">资源列表</a></li><li class="ng-star-inserted"><a class="link" href="presskit" title="我们的联系方式、LOGO 和品牌">宣传资料</a></li><li class="ng-star-inserted"><a class="link" href="https://blog.angular.io/" title="Angular 官方博客">博客</a></li><li class="ng-star-inserted"><a class="link" href="analytics" title="Angular 使用情况分析">使用情况分析</a></li></ul></div><div class="footer-block ng-star-inserted"><h3>帮助</h3><ul><li class="ng-star-inserted"><a class="link" href="https://stackoverflow.com/questions/tagged/angular" title="Stack Overflow: 这里的社区会回答你关于 Angular 的技术问题">Stack Overflow</a></li><li class="ng-star-inserted"><a class="link" href="https://gitter.im/angular/angular" title="和老鸟聊 Angular">Gitter</a></li><li class="ng-star-inserted"><a class="link" href="https://github.com/angular/angular/issues" title="在 github 上报告问题和建议。">报告问题</a></li><li class="ng-star-inserted"><a class="link" href="https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md" title="让我们彼此尊重">行为规范</a></li></ul></div><div class="footer-block ng-star-inserted"><h3>社区</h3><ul><li class="ng-star-inserted"><a class="link" href="events" title="Angular events around the world.">活动</a></li><li class="ng-star-inserted"><a class="link" href="http://www.meetup.com/topics/angularjs/" title="参加聚会，向别的开发人员学习">聚会</a></li><li class="ng-star-inserted"><a class="link" href="https://twitter.com/angular" title="Twitter">Twitter</a></li><li class="ng-star-inserted"><a class="link" href="https://github.com/angular/angular" title="GitHub">GitHub</a></li><li class="ng-star-inserted"><a class="link" href="contribute" title="向 Angular 做贡献">做贡献</a></li></ul></div><div class="footer-block ng-star-inserted"><h3>多语言</h3><ul><li class="ng-star-inserted"><a class="link" href="https://angular.io/" title="English Version.">English Version</a></li><li class="ng-star-inserted"><a class="link" href="https://angular.tw/" title="正體中文版">正體中文版</a></li><li class="ng-star-inserted"><a class="link" href="https://angular.jp/" title="日本語版">日本語版</a></li><li class="ng-star-inserted"><a class="link" href="https://angular.kr/" title="한국어">한국어</a></li></ul></div></div><p>Super-powered by Google ©2010-2020. 代码授权方式：<a href="license" title="License text">MIT-style License</a>. 文档授权方式：<a href="http://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>.</p><p>当前版本：9.0.1-build.79+sha.55f1ef01.</p></aio-footer></footer><div class="cdk-visually-hidden ng-star-inserted"><mat-icon role="img" class="mat-icon notranslate material-icons mat-icon-no-color" aria-hidden="true">&nbsp;</mat-icon></div></aio-shell><noscript><div class="background-sky hero"></div><section id="intro" style="text-shadow:1px 1px #1976d2"><div class="hero-logo"><img src="assets/images/logos/angular/angular.svg" width="250" height="250" alt="Angular"></div><div class="homepage-container"><div class="hero-headline">一套框架，多种平台<br>移动 &amp; 桌面</div></div></section><h2 style="color:red;margin-top:40px;position:relative;text-align:center;text-shadow:1px 1px #fafafa"><b><i>该网站需要浏览器支持 JavaScript</i></b></h2></noscript><script src="runtime-es2015.ee607cf78010348c8334.js" type="module"></script><script src="runtime-es5.ee607cf78010348c8334.js" nomodule="" defer=""></script><script src="polyfills-es5.1494ca908613f3429457.js" nomodule="" defer=""></script><script src="polyfills-es2015.9057a05c650bf60ecbf4.js" type="module"></script><script src="main-es2015.9cd62e243bd182514a19.js" type="module"></script><script src="main-es5.9cd62e243bd182514a19.js" nomodule="" defer=""></script><div class="cdk-live-announcer-element cdk-visually-hidden" aria-atomic="true" aria-live="polite"></div></body></html>